espresso_coffee
espresso_coffee

Reputation: 6110

How to loop over array of objects and check if name exists?

I have array of objects with about 500 records. I would like to loop trough the array of objects and check if object name is equal to one of the elements. Here is example of my array of objects:

data = [
      {
        "row": 23,
        "code": "ERT"
      },
      {
        "row": 45,
        "code": "TTR"
      },
      {
        "row": 90,
        "code": "CXZ"
      }
    ];

Here is what I tried so far:

data.some(function (obj) {
    if(obj.name === "code"){
        return obj[name]; // Return value if name exists
    }
});

I would like to check if name exists in the object. If does, pull the value for that name. My code will produce undefined in the console. Can someone help with this? Is there a way to achieve this?

Upvotes: 1

Views: 3999

Answers (3)

Ariel
Ariel

Reputation: 1436

You can do something like this:

const name = "code";
const data = [
      {
        "row": 23,
        "code": "ERT"
      },
      {
        "row": 45,
        "code": "CXZ"
      },
      {
        "row": 90,
        "code": "TTR"
      },
      {
        "row": 190,
        "code": "CXZ"
      }
    ];

const values = [];

data.forEach(element => {
	if (Object.keys(element).includes(name)) {
  	values.push(element[name]);
  }
});
    
console.log(values);

Object.keys grab all the keys of the object, and then includes searchs the "name" in those keys.

Upvotes: 1

Dacre Denny
Dacre Denny

Reputation: 30370

If I understand your question correctly, then you can achieve this by .filter(), where for each item being filtered, your examine the item's keys (via Object.keys()) to see if it contains any of the keys that you're searching/filtering against:

var namesToCompare = ['name', 'code'];

var data = [
      {
        "row": 23,
        "code": "ERT"
      },
      {
        "row": 45,
        "code": "TTR"
      },
      {
        "row": 90,
        "code": "CXZ"
      },
      {
        "row": 91,
        "code": "ABC", 
        "name" : "code"
      }
    ];
    
var result = data
.filter(item => Object
    .keys(item)
    .find(key => namesToCompare.includes(key)))

console.log('items with keys', namesToCompare, 'in list', result);

Upvotes: 1

clearshot66
clearshot66

Reputation: 2302

Something like so:

data = [
      {
        "row": 23,
        "code": "ERT"
      },
      {
        "row": 45,
        "code": "TTR"
      },
      {
        "row": 90,
        "code": "CXZ"
      }
    ];


$.each(data, function(index,v) {
 $.each(v, function(key,val) {
    if(key == "code")
       console.log(val)
    }
 });
});

Without inner loop:

for (var key in data){

  if(key == "code"){
     console.log(key)
  }
}

Upvotes: 1

Related Questions