var person = {
"name" : "Bronn",
"description" : {
"occupation" : "guardian knight",
"age" : 52
}
}
for(var key in person){
if(person[key] == /*contains json object */){
//do something
}
}
我想循环这个人并检查它的值是否包含单个数据或另一个对象。
最佳答案
你可以使用 Object.keys() , typeof()获得所需的结果并使用 Array's迭代器。
更新:
您使用 Object.prototype.toString.call()
, 获取值的类型。它将返回如下值
const getTypeOfValue = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
console.log('If value is Number then return type is :-', getTypeOfValue(1));
console.log('If value is String then return type is :-', getTypeOfValue('test'));
console.log('If value is Object then return type is :-', getTypeOfValue({key:'value'}));
console.log('If value is Array then return type is :-', getTypeOfValue([{key:'value'}]));
console.log('If value is NULL then return type is :-', getTypeOfValue(null));
console.log('If value is Undefined then return type is :-', getTypeOfValue());
.as-console-wrapper { max-height: 100% !important; top: 0; }
工作演示
var person = {"name": "Bronn","description": {"occupation": "guardian knight","age": 52}},
keys = Object.keys(person);
const getType = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
//ES5
keys.forEach(function(key) {
if (getType(person[key]) === 'object') {
console.log('Find using ES5',person[key]);
}
});
//ES6 syntax
keys.forEach(key => {
if (getType(person[key]) === 'object') {
console.log('Find using ES6', person[key]);
}
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何检查一个对象是否包含另一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46211122/