Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    {"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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading