How to combine JSON objects and unnest array of arrays

I’m trying to fetch apis and combine the json objects into a single variable array that I can loop through.

using .push my variable array ends up as..

[
  [
    {"a":"1"}
  ],
  [
    {"b":"2"}
  ]
]

when i want this..

[
    {"a":"1"},
    {"b":"2"}
]

Here’s my trimmed down code..

var combinedJson = [];

const r1 = fetch(firstJson).then(response => response.json());
const r2 = fetch(secondJson).then(response => response.json());

Promise.all([r1, r2])
  .then(([d1, d2]) => {
    combinedJson.push(d1, d2);
    console.log(combinedJson);
  })
  .catch(error => {
    console.error(error);
  });

>Solution :

I think this is what Array.flat does, but I like to use the spread ... operator to spread arrays so then I can join them again.

var arr1 = [{
  "a": "1"
}]

var arr2 = [{
  "b": "2"
}]

var combined = [...arr1, ...arr2]
console.log(combined)

Leave a Reply