我有一个对象:
{
name: "user",
facebook: {
followers: 2341
},
instagram: {
followers: 5345
}
}
如何在不明确指定路径的情况下获取所有关注者值的数组(例如,它也可以是twitter而不是facebook)
[2341, 5345]
答案 0 :(得分:1)
您可能希望使用for ... in循环来遍历对象的所有属性,然后检查它们是否具有followers属性,最后将该属性添加到列表中。例如:
let myObj = {
name: "user",
facebook: {
followers: 2341
},
instagram: {
followers: 5345
}
}
let followers = [];
for (var prop in myObj) {
if (myObj[prop].hasOwnProperty('followers') && typeof myObj[prop].followers === 'number'){
followers.push(myObj[prop].followers);
}
}
console.log(followers)
答案 1 :(得分:1)
此脚本搜索关键字“followers”的所有匹配项,并将其值添加到数组...
var followers = {
name: "user",
facebook: {
followers: 2341,
test: {
followers: 1,
},
},
instagram: {
followers: 5345
}
};
var followerArray = [];
var getFollowers = function(obj) {
for (var node in obj) {
if (typeof obj[node] === 'object') {
getFollowers(obj[node]);
}
if (node === 'followers') {
followerArray.push(obj[node]);
}
}
}
getFollowers(followers);
console.log(followerArray);