-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.

4
  • 3
    please share expected output and code which you have tried so far Commented May 14, 2019 at 14:54
  • Possible duplicate of Javascript- Iterate over nested objects, getting values and chained keys Commented May 14, 2019 at 14:54
  • What have you tried? Did you even set up a loop? Commented May 14, 2019 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 Commented May 14, 2019 at 15:02

2 Answers 2

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}`)
    })
}

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

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.