0

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);
  });
4
  • .then(([[d1], [d2]]) => Commented Mar 30, 2024 at 12:30
  • i'm sorry what syntax is this? {"a","1"}? Commented Mar 30, 2024 at 12:35
  • @ITgoldman the wrong syntax.. edited. Commented Mar 30, 2024 at 12:45
  • @AlexanderNenashev Tried it, ty, but it's just returning the first entry from each JSON object. Commented Mar 30, 2024 at 12:47

1 Answer 1

0

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)

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

2 Comments

Spread operators worked, thankyou very much. I'll play around again with array.flat and report back (have tried now and earlier but couldn't figure it out).
combined = combined.flat(); worked as well. Ty again.

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.