3

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?

2
  • What's val? Where does .key come from? Commented Nov 27, 2015 at 8:07
  • val is dynamic var lets say b and key comes from the loop inside which should be a Commented Nov 27, 2015 at 8:49

2 Answers 2

1

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;
  });
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use Object.keys() to get keys of an object.

var val = 'val';
var connect_clients = [];

connect_clients.push({
  'a': val
});

function lookup(keyName) {
    var i;

    for ( i = 0; i < connect_clients.length; i++) {
        var keys = Object.keys(connect_clients[i]);

        if(keys.indexOf(keyName) !== -1) {
            return true;
        }
    }

    return false;
}

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.