假设我有以下对象
var myObject = {
index1: {
indexsub1: index1value1,
indexsub2: index1value2,
},
index2: {
indexsub1: index2value1,
indexsub2: index2value2,
},
index3: {
indexsub1: index3value1,
indexsub2: index3value2,
},
}
如何在不知道index1,index2和index3的情况下检查myObject中是否存在值为x的indexsub1。
答案 0 :(得分:2)
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)
);
答案 1 :(得分:1)
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));
答案 2 :(得分:1)
使用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;
}
});