0

I will like to print [4, 5, 2] as the value of supervisors in the following nested array/objects.

var data = {
   supervisors: [
     {
      0: [
          { 
            id: 4, 
            name: "Reporter"
          }
        ]
     },
     {
      1: [
          { 
            id: 5, 
            name: "Officer"
          }
        ]
     },
     {
      2: [
          { 
            id: 2, 
            name: "Coordinator"
          }
        ] 
     },
     ]
};

How can I loop through the data?

7
  • You need Array.map for this. And you obviously need to know how to access properties and array elements. Commented Jul 13, 2021 at 9:15
  • Are you able to fix the thing that's giving you that data structure to just be a simple array of objects? Commented Jul 13, 2021 at 9:16
  • stackoverflow.com/questions/16626735/… here is a related question Commented Jul 13, 2021 at 9:18
  • data.supervisors.flatMap(item => Object.values(item).map(value => value[0].id)) Commented Jul 13, 2021 at 9:21
  • 1
    @mplungjan you nailed it. You can post this as a correct answer Commented Jul 13, 2021 at 9:25

1 Answer 1

0

let data = {
  supervisors: [{
      0: [{
        id: 4,
        name: "Reporter"
      }]
    },
    {
      1: [{
        id: 5,
        name: "Officer"
      }]
    },
    {
      2: [{
        id: 2,
        name: "Coordinator"
      }]
    },
  ]
};

let output = []
data.supervisors.forEach(item => {

  output.push(item[Object.keys(item)][0].id)

});

console.log(output)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.