繁体   English   中英

如何检查在另一个对象中找到的对象的已知索引的值是否存在

[英]how to check if a value of a known index of an object found in another object exist

可以说我有以下对象

var myObject = {
 index1: {
    indexsub1: index1value1,
    indexsub2: index1value2,
 },
 index2: {
    indexsub1: index2value1,
    indexsub2: index2value2,
 },
 index3: {
    indexsub1: index3value1,
    indexsub2: index3value2,
 },
}

如何在不知道index1,index2和index3的情况下,在myObject中是否存在值为x的indexsub1。

 var myObject = { index1: { indexsub1: 1, indexsub2: 2, }, index2: { indexsub1: 3, indexsub2: 4, }, index3: { indexsub1: 5, indexsub2: 6, }, } // key exists and value equal console.log( Object.keys(myObject).some(key => myObject[key]['indexsub1'] === 1) ); // key exists but value not equal console.log( Object.keys(myObject).some(key => myObject[key]['indexsub1'] === 7) ); // key doesn't exist console.log( Object.keys(myObject).some(key => myObject[key]['indexsub7'] === 7) ); 

 var myObject = { index1: { indexsub1: 1, indexsub2: 2, }, index2: { indexsub1: 3, indexsub2: 4, }, index3: { indexsub1: 5, indexsub2: 6, }, }; function hasKeyValue(key, value) { for (var prop in myObject) { if (myObject[prop][key] === value) return true; } return false; } console.log(hasKeyValue("indexsub1", 5)); console.log(hasKeyValue("indexsub1", 7)); 

使用Object.keys()可以获得对象的所有键。 这将产生一个数组['index1', 'index2', 'index3']

Object.keys(myObject)

现在,您可以使用它来访问所有子对象,并在那里检查属性indexsub1是否具有某个值:

const hasX = Object.keys(myObject).any(index => {
  const subObject = myObject[index];
  if (subObject.indexsub1 == 'x') {
    return true;
  } else {
    return false;
  }
});

暂无
暂无

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

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