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

后端 未结 25 1165
借酒劲吻你
借酒劲吻你 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 08:50

    As the OP has asked the question if the key exists or not.

    A more elegant solution that will return boolean using ES6 reduce function can be

    const magenicVendorExists =  vendors.reduce((accumulator, vendor) => (accumulator||vendor.Name === "Magenic"), false);
    

    Note: The initial parameter of reduce is a false and if the array has the key it will return true.

    Hope it helps for better and cleaner code implementation

    0 讨论(0)
  • 2020-11-22 08:50

    var without2 = (arr, args) => arr.filter(v => v.id !== args.id); Example:

    without2([{id:1},{id:1},{id:2}],{id:2})

    Result: without2([{id:1},{id:1},{id:2}],{id:2})

    0 讨论(0)
  • 2020-11-22 08:53

    const VENDORS = [{ Name: 'Magenic', ID: 'ABC' }, { Name: 'Microsoft', ID: 'DEF' }];
    
    console.log(_.some(VENDORS, ['Name', 'Magenic']));
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>

    0 讨论(0)
  • 2020-11-22 08:53

    You can use lodash. If lodash library is too heavy for your application consider chunking out unnecessary function not used.

    let newArray = filter(_this.props.ArrayOne, function(item) {
                        return find(_this.props.ArrayTwo, {"speciesId": item.speciesId});
                    });
    

    This is just one way to do this. Another one can be:

    var newArray=  [];
         _.filter(ArrayOne, function(item) {
                            return AllSpecies.forEach(function(cItem){
                                if (cItem.speciesId == item.speciesId){
                                newArray.push(item);
                              }
                            }) 
                        });
    

    console.log(arr);

    The above example can also be rewritten without using any libraries like:

    var newArray=  [];
    ArrayOne.filter(function(item) {
                    return ArrayTwo.forEach(function(cItem){
                        if (cItem.speciesId == item.speciesId){
                        newArray.push(item);
                      }
                    }) 
                });
    console.log(arr);
    

    Hope my answer helps.

    0 讨论(0)
  • 2020-11-22 08:56
    const a = [{one:2},{two:2},{two:4}]
    const b = a.filter(val => "two" in val).length;
    if (b) {
       ...
    }
    
    0 讨论(0)
  • 2020-11-22 08:57

    Alternatively you can do:

    const find = (key, needle) => return !!~vendors.findIndex(v => (v[key] === needle));
    
    0 讨论(0)
提交回复
热议问题