简体   繁体   English

制作嵌套对象数组并检查objs中是否存在该键

[英]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. 每当我将现有密钥传递给我的函数时,我都会变false

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? 有什么问题吗?

connect_clients[i].key refers to the actual property named key , not the keys of the object. connect_clients[i].key引用名为key的实际属性,而不是对象的键。

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. 对于这种情况,您可以使用Object.keys来获取对象的键数组,并使用Array.prototype.some确保至少有一个对象具有键。 For example, 例如,

function lookup(name) {
  return connect_clients.some(function(client) {
    return Object.keys(client).indexOf(name) !== -1;
  });
}

Use Object.keys() to get keys of an object. 使用Object.keys()获取对象的键。

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'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM