检查object是否存在于另一个对象中

Check if object exists in another object

本文关键字:一个对象 于另 存在 object 是否 检查      更新时间:2023-09-26

我有一个像这样的对象:

var obj = {
 heroes: {
        "1": {
          label: "Spiderman"
        },
        "2": {
          label: "Iron Man"
        },
       }
}

我想知道的是,在obj.heroes.

中是否存在一个对象,例如2。

我试过了,但是没有成功:

var name = "heroes"; //Will be a for-loop later
try {
        if(name["2"] in obj) 
            console.log("There is an 2nd superhero!");
    } catch(e) {console.log(e);}

. ."Cannot read property '2' of undefined"

我希望你能帮助我。由于

Try

   if ("2" in obj[name]){
      console.log("There is an 2nd superhero!");
   }

但是如果你试图识别计数,最好使用数组

var obj = {
   heroes: [
            {label: "Spiderman"},
            {label: "Iron Man"}
           ]
}

核对
if (obj[name].length > 1) {
    console.log("There is an 2nd superhero!");
}

你可以这样做:

try {
  console.log(obj.heroes["2"]);
} catch (e) {
  console.log('nope :c');
}

但是,最好将heroes存储为数组:

var obj = {
  heroes: [
    {
      label: 'Spiderman'
    },
    {
      label: 'Ironman'
    }
  ]
};

使用数组更有意义,因为heroes由多个hero对象组成。

如果第二个超级英雄不存在,则条件返回false。

if(obj.heroes["2"]) 
    console.log("There is an 2nd superhero!");

或:

var count = 0;
for (var x in obj.heroes) {
    if (obj.heroes.hasOwnProperty(x)) {
       count++;
    }
}
console.log("You see "+ count +" heroes.");

这段代码会帮你找到它

var delve = function(object, property, dodge) {
        if (!dodge) dodge = object;
        for (var i in object) {
            if (object[i] === dodge) continue;
            if (typeof(object[i]) == typeof({})) this.delve(object[i], property, dodge)
            if (i == property) console.log(object[i]);
        }
    }
delve(heroes,'2')