var person = {
"name" : "Bronn",
"description" : {
"occupation" : "guardian knight",
"age" : 52
}
}
for(var key in person){
if(person[key] == /*contains json object */){
//do something
}
}
Run Code Online (Sandbox Code Playgroud)
我想循环这个人并检查它的值是否包含单个数据或另一个对象。
您可以使用Object.keys()、typeof()来获得所需的结果并使用Array 的迭代器。
更新 :
您使用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());Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
工作演示
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]);
}
});Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }Run Code Online (Sandbox Code Playgroud)
它只是普通对象而不是 JSON。并使用过滤对象值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)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6458 次 |
| 最近记录: |