var person = {
"name" : "Bronn",
"description" : {
"occupation" : "guardian knight",
"age" : 52
}
}
for(var key in person){
if(person[key] == /*contains json object */){
//do something
}
}
我想循环此人并检查其值是否包含单个数据或其他对象。
答案 0 :(得分:3)
您可以使用Object.keys(),typeof()获取重新获得的结果并使用Array's迭代器。
<强>演示强>
var person = {"name": "Bronn","description": {"occupation": "guardian knight","age": 52}},
keys =Object.keys(person);
//ES5
keys.forEach(function(key) {
if (typeof(person[key]) == 'object') {
console.log('Find using ES5',person[key]);
}
});
//ES6 syntax
keys.forEach(key => {
if (typeof(person[key]) == 'object') {
console.log('Find using ES6',person[key]);
}
});
答案 1 :(得分:2)
它只是普通的对象而不是JSON.And filter object values和typeof() == object
。已显示对象的已过滤数组的长度是否存在
var person = {
"name" : "Bronn",
"description" : {
"occupation" : "guardian knight",
"age" : 52
}
}
console.log('its contains any object=',Object.values(person).filter(a=> typeof(a) == 'object').length > 0)
答案 2 :(得分:1)
只需检查下面的构造函数
for(var key in person){
if(person[key].constructor == Object){
//do something
}
}
答案 3 :(得分:1)
您可以使用typeof
查看object
,但您还需要检查该值,因为null
是一个对象和一个值。
var person = { foo: null, name: "Bronn", description: { occupation: "guardian knight", age: 52 } },
keysOfObjects = Object.keys(person).filter(key => typeof person[key] == 'object'),
wantedKeys = Object.keys(person).filter(key => person[key] && typeof person[key] == 'object');
console.log(keysOfObjects);
console.log(wantedKeys);
.as-console-wrapper { max-height: 100% !important; top: 0; }