gpt4 book ai didi

javascript - 如何检查一个对象是否包含另一个对象?

转载 作者:行者123 更新时间:2023-11-30 07:32:35 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com