Home > Enterprise >  How can I create an array of objects by extracting an array that is inside another array of objects
How can I create an array of objects by extracting an array that is inside another array of objects

Time:05-23

I am trying to create a new array based on another array of objects that has another array of objects within its keys. To explain myself. I have the following interfaces:

export interface  RouteElement{
  component?:  Type<any>;
  path: string;
  label: string;
  data?:{ message?: string}

}

export interface  RouterNodeElement{
  label: string;
  children: RouteElement[]
}

and I have this array

routerNodes: [ { label: "NodeRoute", children: [ { path: 'child', label: 'child',  data: { message: 'child' }}] } ]

So basically I have an array of routerNodes with the key inside "Children" and what I want is to extract all the "Children" and create a new array with each children of each routerNodel but I can't find a way to flatten that object.

const flatRouterNodes = this.routerNodes.map( route => {
    return route.children.map( child => child);
  });

What I got

enter image description here

CodePudding user response:

Is this what you're looking for?

const routeNodes = [ { label: "NodeRoute", children: [ { path: 'child', label: 'child',  data: { message: 'child' }}] }, { label: "R2", children: [ { path: 'child', label: 'child',  data: { message: 'child' }}] } ]
routeNodes.reduce((acc, curr) => [...acc, ...curr.children], [])
// [
//  { path: 'child', label: 'child', data: { message: 'child' } },
//  { path: 'child', label: 'child', data: { message: 'child' } }
// ]

You can also use flatMap:

routerNodes.flatMap((item) => item.children)

Note that flatMap doesn't work in IE 11, but seems to be more performant than reduce (see benchmark).

CodePudding user response:

You can use reduce and forEach

let routerNodes = [ { label: "NodeRoute", children: [ { path: 'child', label: 'child',  data: { message: 'child' }}] } ]

let childerns = routerNodes.reduce((acc,curr)=>{
  curr.children.forEach(child => acc.push(child))
  return acc
},[])

console.log(childerns)


let routerNodes = [{label: "NodeRoute",children: [{path: 'child',label: 'child',data: {message: 'child'}}]},{label: "NodeRoute2",children: [{path: 'child2',label: 'child2',data: {message: 'child2'}}]}]

let childerns = routerNodes.flatMap(curr => curr.children)

console.log(childerns)

You can use flatMap as well

  • Related