Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making nested objects array and checking if the key exists in objs

I am trying to check if the keys exits in array of objects. I am getting false each time when I pass existing key to my function.

var connect_clients = [];
connect_clients.push({
  'a': val
});

function lookup(name) {
  for (var i = 0, len = connect_clients.length; i < len; i++) {
    if (connect_clients[i].key === name)
      return true;
  }
  return false;
}

console.log(lookup('a'));

Is there anything wrong?


1 Answers

connect_clients[i].key refers to the actual property named key, not the keys of the object.

For this case, you can use Object.keys to get an array of keys of an object and use Array.prototype.some to make sure that at least one of the objects has the key. For example,

function lookup(name) {
  return connect_clients.some(function(client) {
    return Object.keys(client).indexOf(name) !== -1;
  });
}
like image 94
thefourtheye Avatar answered Apr 29 '26 03:04

thefourtheye