-1

I have the following array of objects which also contains objects, available to me seen in the console as:

Array(2)
0 {GK: {job_numbers: ["56764"]}}
1 {AK: {job_numbers: ["12345", "5678", "78909"]}, MATT: {job_numbers: ["12345"]}}

Now I want to loop through this array in such a manor that I go to each object, and then also loop the elements inside.

For example,

I want to loop the array and get GK and its job numbers, then also get AK and its job numbers as well as MATT and its job numbers.

Khokhar
  • 149
  • 2
  • 9
  • 3
    please share expected output and code which you have tried so far – Naga Sai A May 14 '19 at 14:54
  • Possible duplicate of [Javascript- Iterate over nested objects, getting values and chained keys](https://stackoverflow.com/questions/17231118/javascript-iterate-over-nested-objects-getting-values-and-chained-keys) – Kévin Bibollet May 14 '19 at 14:54
  • What have you tried? Did you even set up a loop? – Scott Marcus May 14 '19 at 14:55
  • I don't think that data structure is correct, if the 'GK' or 'MATT' supposed to be names, your nested object should look something like this: {name: 'MATT', job_numbers: [...]}, otherwise you have to explicitly use property names – alexlz May 14 '19 at 15:02

2 Answers2

1

You can display each key and value by looping over each item in the array, then over the keys in each of the items:

const arr = [{GK: {job_numbers: ["56764"]}},{AK: {job_numbers: ["12345", "5678", "78909"]}, MATT: {job_numbers: ["12345"]}}]

for(var i in arr) {
    const obj = arr[i];
    Object.keys(obj).forEach((job, index) => {
        console.log(`${job}: ${obj[job].job_numbers}`)
    })
}
Kobe
  • 6,226
  • 1
  • 14
  • 35
0

try

d.flatMap(o=> Object.keys(o).map(k=> `${k}: ${o[k].job_numbers}`));

let d=[{GK: {job_numbers: ["56764"]}}, {AK: {job_numbers: ["12345", "5678", "78909"]}, MATT: {job_numbers: ["12345"]}}
]

let r = d.flatMap(o=> Object.keys(o).map(k=> `${k}: ${o[k].job_numbers}`));

console.log(r);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345