-2

INPUT

[0]: [{}, {}],
[1]: [{}, {}],
[2]: [{}]

I have index 0, 1 and 2 with array of objects. Now I need to merge all these index values into a single array of object

Expected O/P

[{}, {}, {}, {}, {}]

Sundar
  • 135
  • 1
  • 1
  • 4
  • 3
    use [flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) – decpk Sep 09 '21 at 04:05
  • Duplicate of [Converting an array of single object arrays, to an array of objects](/q/63344699/4642212). Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and use the available static and instance methods of [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Sep 09 '21 at 05:49

3 Answers3

1

let arr = [
  [{
    key1: "value1"
  }, {
    key2: "value2"
  }],
  [{
    key3: "value3"
  }, {
    key4: "value4"
  }],
  [{
    key5: "value5"
  }]
];

arr = arr.flat();

console.log(arr);
Vineet Desai
  • 750
  • 4
  • 14
-1

Here's just one solution like you need:

let a = {
  0: [{}, {}],
  1: [{}, {}],
  2: [{}]
}

let values = []
for (var x in a)
{
    a[x].map(p => values.push(p))
}
console.log(values)  //[{}, {}, {}, {}, {}]

Make sure to handle each case, validate if it's an array then loop over it.

Harsh Patel
  • 5,503
  • 7
  • 33
  • 62
-1

You can do a one liner using the reduce:

const obj = {
  0: [{}, {}],
  1: [{}, {}],
  2: [{}]
}

const arr = Object.values(obj).reduce((acc, curr) => ([...acc, ...curr]), [])
console.log(arr)
Yosvel Quintero Arguelles
  • 17,270
  • 4
  • 37
  • 42
Karma Blackshaw
  • 773
  • 5
  • 19