0

I have an object:

{
name: "user",
facebook: {
    followers: 2341
},
instagram: {
    followers: 5345
}
}

How can I get an array of all followers values without explicitely specifying the path (e.g. It could also be twitter instead of facebook)

[2341, 5345]
Chris
  • 13,100
  • 23
  • 79
  • 162
  • Is their a possibilty of any nesting, or is the structure you show limited to that depth? – JAAulde May 24 '17 at 13:03
  • @JAAulde yes, there may be nesting. Thanks for the hint – Chris May 24 '17 at 13:04
  • Your answer is [here](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – Abk May 24 '17 at 13:11

2 Answers2

1

You're probably going to want to use a for .. in loop to loop over all the properties of the object, then check if they have a followers property, and finally add that property to a list. E.g.:

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)
James Kraus
  • 3,349
  • 20
  • 27
1

This script searches for all occurrences of the keyword "followers" and adds it value to the array...

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);
Robert
  • 426
  • 1
  • 4
  • 11