0

I'm parsing a JSON which does not start with [] brackets. Instead you see the following:

{
  "result":{
    "heroes":[
      {
        "name":"npc_dota_hero_antimage",
        "id":1,
        "localized_name":"Anti-Mage"
      },
      ...
    ]
  }
}

There are a total of 115 items.

When trying to use ES6's spread operator ... like so,

const endpoint = './heroes.json'
let heroes = []
fetch(endpoint)
  .then(blob => blob.json())
  .then(data => heroes.push(...data))

I will not be able to iterate over the JSON due to result and heroes shielding the objects.

Is there a way to use the spread operator on the above JSON structure? If so, how then would i console log to give me the first item's name of Anti-Mage ?

toddg
  • 2,863
  • 2
  • 18
  • 33
HJW
  • 1,012
  • 2
  • 13
  • 32

1 Answers1

1

Just use the spread on the property that is an array:

fetch('./heroes.json')
  .then(blob => blob.json())
  .then(data => ...data.result.heroes)
  .then(heroes => console.log(heroes));

Consider this:

const nested = {
  foo: {
    bar: {
      fizz: {
        buzz: ["hello", "world"]
      }
    }
  }
};

function test(first, second) {
  console.log(`first: ${first} | second: ${second}`);
}
test(...nested.foo.bar.fizz.buzz);
zero298
  • 25,467
  • 10
  • 75
  • 100
  • @ zero298 Since I'm fetching the JSON from another site I can't really make a const/variable out of it. Adding the `.then(heroes => console.log(heroes));` however works to be able to reach it. Why ? How come I can't reach the value with an outside-console.log, but pairing it with `.then` within the function works ? – HJW Feb 26 '18 at 23:18
  • @Helle You need to read this question: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086/691711). – zero298 Feb 26 '18 at 23:23
  • Makes a lot of sense, thank you for that. I have trouble implementing that in this simple `fetch`. Can you point me in the right direction? – HJW Feb 26 '18 at 23:59