“spread operator”迭代JSON的子集

时间:2018-02-26 20:57:00

标签: javascript arrays json

我正在解析一个不以[]括号开头的JSON。相反,您会看到以下内容:

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

共有115件商品。

尝试使用ES6的扩展运算符...时,

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

由于resultheroes屏蔽了对象,我将无法迭代JSON。

有没有办法在上面的JSON结构中使用spread运算符? 如果是这样,我如何控制日志给我第一个项目的名称Anti-Mage

1 个答案:

答案 0 :(得分:1)

只需在 数组的属性上使用点差:

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

考虑一下:

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

function test(first, second) {
  console.log(`first: ${first} | second: ${second}`);
}
test(...nested.foo.bar.fizz.buzz);