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

Ang*_*ger 3 javascript

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)

我想循环这个人并检查它的值是否包含单个数据或另一个对象。

Nar*_*hav 6

您可以使用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)

  • `typeof` 将给出一个 `object`,即使它是一个数组。如果你不需要数组怎么办? (2认同)

pra*_*nth 2

它只是普通对象而不是 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)