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

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

    To compare one object to another, I combine a for in loop (used to loop through objects) and some(). You do not have to worry about an array going out of bounds etc, so that saves some code. Documentation on .some can be found here

    var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
    var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
    var  objectsFound = [];
    
    for(let objectNumber in productList){
        var currentId = productList[objectNumber].id;   
        if (theDatabaseList.some(obj => obj.id === currentId)) {
            // Do what you need to do with the matching value here
            objectsFound.push(currentId);
        }
    }
    console.log(objectsFound);
    

    An alternative way I compare one object to another is to use a nested for loop with Object.keys().length to get the amount of objects in the array. Code below:

    var productList = [{id: 'text3'}, {id: 'text2'}, {id: 'text4', product: 'Shampoo'}]; // Example of selected products
    var theDatabaseList = [{id: 'text1'}, {id: 'text2'},{id: 'text3'},{id:'text4', product: 'shampoo'}];    
    var objectsFound = [];
    
    for(var i = 0; i < Object.keys(productList).length; i++){
            for(var j = 0; j < Object.keys(theDatabaseList).length; j++){
            if(productList[i].id === theDatabaseList[j].id){
                objectsFound.push(productList[i].id);
            }       
        }
    }
    console.log(objectsFound);
    

    To answer your exact question, if are just searching for a value in an object, you can use a single for in loop.

    var vendors = [
        {
          Name: 'Magenic',
          ID: 'ABC'
         },
        {
          Name: 'Microsoft',
          ID: 'DEF'
        } 
    ];
    
    for(var ojectNumbers in vendors){
        if(vendors[ojectNumbers].Name === 'Magenic'){
            console.log('object contains Magenic');
        }
    }
    

提交回复
热议问题