Home > Enterprise >  How to iterate over second level of an Array to get a single array as final result?
How to iterate over second level of an Array to get a single array as final result?

Time:01-16

I want to get a final Array from the second level of my array

Students =
[{
  "name":"Ashish",
  "lastname":"Boora",
  "detail":[
            {"id":1,"sid":3,"pid":5},
            {"id":2,"sid":4,"pid":6},
            {"id":7,"sid":8,"pid":9}
          ]
},{
  "name":"Harsh",
  "lastname":"Deep",
  "detail":[
            {"id":11,"sid":13,"pid":15},
            {"id":12,"sid":14,"pid":16},
            {"id":17,"sid":18,"pid":19}
          ]
},{
  "name":"Rajat",
  "lastname":"Sharma",
},
{ 
  "name":"Sumit",
  "lastname":"Verma",
  "detail":[
            {"id":21,"sid":23,"pid":25},
            {"id":22,"sid":24,"pid":26},
            {"id":27,"sid":28,"pid":29}
          ]
}]

I want to get final output as array of all the id in detail of each element of the array as

ids = [1,2,7,11,12,17,21,22,27]

Please note that there are some elements in the main array for which the key 'detail' is missing.

CodePudding user response:

You can use the Array.prototype.map() method to create a new array that contains only the id properties of the detail objects, and then use the Array.prototype.flat() method to flatten the resulting array of arrays into a single array.

let Array = [{
  "name":"Ashish",
  "lastname":"Boora",
  "detail":[
            {"id":1,"sid":3,"pid":5},
            {"id":2,"sid":4,"pid":6},
            {"id":7,"sid":8,"pid":9}
          ]
},{
  "name":"Harsh",
  "lastname":"Deep",
  "detail":[
            {"id":11,"sid":13,"pid":15},
            {"id":12,"sid":14,"pid":16},
            {"id":17,"sid":18,"pid":19}
          ]
},{
  "name":"Rajat",
  "lastname":"Sharma",
},
{ 
  "name":"Sumit",
  "lastname":"Verma",
  "detail":[
            {"id":21,"sid":23,"pid":25},
            {"id":22,"sid":24,"pid":26},
            {"id":27,"sid":28,"pid":29}
          ]
}];

let ids = Array.map(item => item.detail)
               .flat()
               .map(item => item.id);
console.log(ids);

The .flat() method is not supported in all browser, so you can use a polyfill or use a different method like .reduce() as an alternative.

let ids = Array.reduce((acc, val) => {
  if (val.detail) {
    acc.push(...val.detail.map(item => item.id));
  }
  return acc;
}, []);
console.log(ids);

In this example, the map() method is used to extract the detail property of each element in the Array. Then, the flat() method is used to flatten the resulting array of arrays into a single array. Finally, the map() method is used again to extract the id property of each object in the detail array. The result will be an array of ids as [1,2,7,11,12,17,21,22,27]

CodePudding user response:

yourArray
    .flatMap((person) => // Map over every person
        person.detail // Get detail array, if it exists
          ?.map((detail) => detail.id)) // Return id for each detail entry
    .filter(Number) // Removing undefined entries caused by people with no `details`

CodePudding user response:

Let me first point out that Array is a terrible name for an instance of the class Array. What if you want to access the class instead of the instance? For example to use the Array.from() function.

A variable name should be as closely scoped as possible, and Array is the largest scope you can give it. The only thing it tells you is that there is a collection of things. It tells us nothing of what the collection is about. In your scenario I see the properties name and lastname. I'll assume we're working with a list of people, so a better variable name would be people. This name tells us that we're working with a list, because it's in plural form, but also what's in the list.

You may even be able to specify it further. Are those people all musicians, actors, singers, athletes, etc. Then use that as variable name.

With this rant out of the way, let's get to the answer.


A combination of flatMap() and map() solves your issue:

const ids = people.flatMap(person => person.detail || []).map(detail => detail.id);

Here people.flatMap(...) will iterate over all people. For each person we get their detail, if it's not present we'll use an empty list person => person.detail || []. This will result in one large array containing the detail elements of all people.

We then iterate over this list and map each detail to its id with .map(detail => detail.id). This produces a list with just detail ids.

  • Related