Beginner
Beginner

Reputation: 9095

extracting object from array of array using es6

how can i return an array of objects taking from array of again one more level array. I am using push.

is there any better way to achieve this

let a = [{b: [{c: "k"}]}]

let o = []

a.forEach(so => {so.b.forEach(obc => o.push(obc))})

console.log(o)

Upvotes: 0

Views: 66

Answers (2)

CertainPerformance
CertainPerformance

Reputation: 370679

I'd use flatMap() instead:

const a = [{
    b: [{
      foo: 'foo'
    }]
  },
  {
    b: [{
        c: "k"
      },
      {
        bar: 'bar'
      }
    ]
  }
];

const o = a.flatMap(({ b }) => b);
console.log(o);

(but this is a relatively new method, so if you want to use it and still support older environments, be sure to include a polyfill)

Lacking that, you can also improve your existing code by using concat() with the inner array instead of iterating over each inner item:

const a = [{
    b: [{
      foo: 'foo'
    }]
  },
  {
    b: [{
        c: "k"
      },
      {
        bar: 'bar'
      }
    ]
  }
];

let o = [];
a.forEach(({ b }) => {
  o = o.concat(b);
});
console.log(o);

Upvotes: 4

mrsWhite
mrsWhite

Reputation: 79

Try

let a = [{b: [{c: "k"}]}]

let o =a[0].b
console.log(o)

Upvotes: -1

Related Questions