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

后端 未结 25 1615
借酒劲吻你
借酒劲吻你 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: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.

提交回复
热议问题