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?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Wacademy
  • 101
  • 2
  • 13
  • Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=javascript+get+nested+object+values+site%3Astackoverflow.com)<<<*** and if you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Jul 13 '21 at 09:15
  • You need `Array.map` for this. And you obviously need to know how to access properties and array elements. –  Jul 13 '21 at 09:15
  • Are you able to fix the thing that's giving you that data structure to just be a simple array of objects? – Andy Jul 13 '21 at 09:16
  • https://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties here is a related question – TinsG Jul 13 '21 at 09:18
  • `data.supervisors.flatMap(item => Object.values(item).map(value => value[0].id))` – mplungjan Jul 13 '21 at 09:21
  • 1
    @mplungjan you nailed it. You can post this as a correct answer – Wacademy Jul 13 '21 at 09:25
  • Actually I cannot since I closed this question as a duplicate. Next time please have a search around SO before asking :) – mplungjan Jul 13 '21 at 09:26
  • Ok I am new to Stackoverflow. Thanks all the same – Wacademy Jul 13 '21 at 09:27

1 Answers1

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)
Rui Costa
  • 417
  • 2
  • 11