0

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)

2 Answers 2

4

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

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

1 Comment

without using polyfill anyother methods or its better to use array.push
-1

Try

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

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

2 Comments

i don't want to statically code as 0 as index. I have given a snippet to understand the question
you can add param with index you want

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.