如何使用javascript中的fetch命令获取json并将其添加到数组中

问题描述 投票:0回答:1

我是javascript的新手,我不太确定如何将json添加到数组中。我使用fetch命令获取json。这是我获取json文件的代码

fetch("event.json")
  .then(response => response.json())
  .then(json => console.log(json));

我现在不确定如何将它添加到数组中,任何帮助都将不胜感激!

这是我正在抓的json

{
   "id": "1",
   "name": "Tim",
   "email": "[email protected]",
   "event":[{"id":1,"name":"HomeShow"}]
}

它是一个包含多个人的大型json文件。我需要获取此文件,然后将其添加到数组中,以便我可以迭代它并取出某些值

javascript arrays json object ecmascript-6
1个回答
0
投票

如果我理解正确,你的JSON文件,event.json(应该是events.json?),包含一个对象数组,如下所示:

[
  {
    "id": "1",
    "name": "Tim",
    "email": "[email protected]",
    "event": [{ "id": 1, "name": "HomeShow" }]
  },
  {
    "id": "2",
    "name": "John",
    "email": "[email protected]",
    "event": [{ "id": 1, "name": "HomeShow" }]
  }
]

然后,要过滤数据,您可以在承诺的回调中执行此操作:

fetch('event.json')
  .then(res => res.json())
  .then(events => events.filter(event => event.name !== 'John'))

请注意,此语句将返回一个promise,该promise将在未来的某个时间具有(已过滤的)数据(因为它是异步的)。

为了能够以后使用该数据,您可以将其包装在函数中,返回promise并在返回值上使用.then来使用数据:

function getFilteredEvents() {
  return fetch('event.json')
    .then(res => res.json())
    .then(events => events.filter(event => event.name !== 'John'))
}

getFilteredEvents().then(filteredEvents => console.log(filteredEvents))
© www.soinside.com 2019 - 2024. All rights reserved.