How to determine if Javascript array contains an object with an attribute that equals a given value?

后端 未结 25 1213
借酒劲吻你
借酒劲吻你 2020-11-22 08:17

I have an array like

vendors = [{
    Name: \'Magenic\',
    ID: \'ABC\'
  },
  {
    Name: \'Microsoft\',
    ID: \'DEF\'
  } // and so on... 
];


        
相关标签:
25条回答
  • 2020-11-22 09:05

    Here's the way I'd do it

    const found = vendors.some(item => item.Name === 'Magenic');
    

    array.some() method checks if there is at least one value in an array that matches criteria and returns a boolean. From here on you can go with:

    if (found) {
    // do something
    } else {
    // do something else
    }
    
    0 讨论(0)
  • 2020-11-22 09:05

    May be too late, but javascript array has two methods some and every method that returns a boolean and can help you achieve this.

    I think some would be most appropriate for what you intend to achieve.

    vendors.some( vendor => vendor['Name'] !== 'Magenic' )
    

    Some validates that any of the objects in the array satisfies the given condition.

    vendors.every( vendor => vendor['Name'] !== 'Magenic' )
    

    Every validates that all the objects in the array satisfies the given condition.

    0 讨论(0)
  • 2020-11-22 09:06

    You can try this its work for me.

    const _ = require('lodash');
    
    var arr = [
      {
        name: 'Jack',
        id: 1
      },
      {
        name: 'Gabriel',
        id: 2
      },
      {
        name: 'John',
        id: 3
      }
    ]
    
    function findValue(arr,value) {
      return _.filter(arr, function (object) {
        return object['name'].toLowerCase().indexOf(value.toLowerCase()) >= 0;
      });
    }
    
    console.log(findValue(arr,'jack'))
    //[ { name: 'Jack', id: 1 } ]
    
    0 讨论(0)
  • 2020-11-22 09:09

    No loop necessary. Three methods that come to mind:

    Array.prototype.some()

    This is the most exact answer for your question, i.e. "check if something exists", implying a bool result. This will be true if there are any 'Magenic' objects, false otherwise:

    let hasMagenicVendor = vendors.some( vendor => vendor['Name'] === 'Magenic' )
    

    Array.prototype.filter()

    This will return an array of all 'Magenic' objects, even if there is only one (will return a one-element array):

    let magenicVendors = vendors.filter( vendor => vendor['Name'] === 'Magenic' )
    

    If you try to coerce this to a boolean, it will not work, as an empty array (no 'Magenic' objects) is still truthy. So just use magenicVendors.length in your conditional.

    Array.prototype.find()

    This will return the first 'Magenic' object (or undefined if there aren't any):

    let magenicVendor = vendors.find( vendor => vendor['Name'] === 'Magenic' );
    

    This coerces to a boolean okay (any object is truthy, undefined is falsy).


    Note: I'm using vendor["Name"] instead of vendor.Name because of the weird casing of the property names.

    Note 2: No reason to use loose equality (==) instead of strict equality (===) when checking the name.

    0 讨论(0)
  • 2020-11-22 09:10

    No need to reinvent the wheel loop, at least not explicitly (using arrow functions, modern browsers only):

    if (vendors.filter(e => e.Name === 'Magenic').length > 0) {
      /* vendors contains the element we're looking for */
    }
    

    or, better yet:

    if (vendors.some(e => e.Name === 'Magenic')) {
      /* vendors contains the element we're looking for */
    }
    

    EDIT: If you need compatibility with lousy browsers then your best bet is:

    if (vendors.filter(function(e) { return e.Name === 'Magenic'; }).length > 0) {
      /* vendors contains the element we're looking for */
    }
    
    0 讨论(0)
  • 2020-11-22 09:10

    You have to loop, there is no way around it.

    function seekVendor(vendors, name) {
      for (var i=0, l=vendors.length; i<l; i++) {
        if (typeof vendors[i] == "object" && vendors[i].Name === name) {
          return vendors[i];
        }
      }
    }
    

    Of course you could use a library like linq.js to make this more pleasing:

    Enumerable.From(vendors).Where("$.Name == 'Magenic'").First();
    

    (see jsFiddle for a demo)

    I doubt that linq.js will be faster than a straight-forward loop, but it certainly is more flexible when things get a little more complicated.

    0 讨论(0)
提交回复
热议问题