[英]how to check if a value of a known index of an object found in another object exist
Lets say I have the following object 可以说我有以下对象
var myObject = {
index1: {
indexsub1: index1value1,
indexsub2: index1value2,
},
index2: {
indexsub1: index2value1,
indexsub2: index2value2,
},
index3: {
indexsub1: index3value1,
indexsub2: index3value2,
},
}
How can I check if there exist an indexsub1 in myObject where the value is x without knowing the index1, index2, and index3. 如何在不知道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));
with Object.keys()
you can get all keys of an object. 使用Object.keys()
可以获得对象的所有键。 This will produce an Array ['index1', 'index2', 'index3']
. 这将产生一个数组['index1', 'index2', 'index3']
。
Object.keys(myObject)
now you can use this to access all sub-objects, and there check if the property indexsub1
has a certain value: 现在,您可以使用它来访问所有子对象,并在那里检查属性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.