删除JSON对象数组的第一个元素

时间:2019-06-01 15:15:45

标签: javascript arrays json reactjs fetch

我正在努力寻找一种方法来缩减此JSON数组,以便可以使用剩余的值。以下是从我正在获取的API中返回的信息,我希望删除多余的信息,因此我只拥有一个包含LGA结果的数组。真的不确定从哪里开始。

{
  "query": {
    "offence": "Dangerous Operation of a Vehicle",
    "area": "",
    "age": "",
    "year": "",
    "gender": ""
  },
  "result": [
    {
      "LGA": "Aurukun Shire Council",
      "total": 156,
      "lat": -13.354875,
      "lng": 141.729058
    },
    {
      "LGA": "Balonne Shire Council",
      "total": 99,
      "lat": -28.464607,
      "lng": 148.189292
    },
    {
      "LGA": "Yarrabah Shire Council",
      "total": 28,
      "lat": -16.910135,
      "lng": 145.868659
    }
  ]
}

5 个答案:

答案 0 :(得分:1)

您可以使用Array​.prototype​.map函数来转换结果:

const response = getYourJsonFromAPI()
response.result.map(result => result.LGA)

返回:

["Aurukun Shire Council", "Balonne Shire Council", "Yarrabah Shire Council"]

答案 1 :(得分:0)

我不确定您如何从API获得响应,但是您可以尝试:

console.log(response.data.result);

答案 2 :(得分:0)

You can try:

response.data.result = response.data.result.slice(1)

答案 3 :(得分:0)

例如,如果只需要LGA值,则可以使用类似这样的方法:

let parsedJson = JSON.parse(json);                //parse json to object
let onlyLGAValues = {};                           //create a new dictionary

parsedJson.result.forEach(function(key, index){   //for each result
    onlyLGAValues[index] = key.LGA;               //push the LGA value in the new dictionary
}); 

console.log(onlyLGAValues);

预期输出:

{0: "Aurukun Shire Council", 1: "Balonne Shire Council", ... 77: "Yarrabah Shire Council"}

答案 4 :(得分:0)

如果我正确阅读了您的问题,则希望获得一个包含string属性的LGA数组:

const data = {
  query: {
    offence: "Dangerous Operation of a Vehicle",
    area: "",
    age: "",
    year: "",
    gender: ""
  },
  result: [{}, {}] // your current large array
};

const lgaArray = data.result.map(({ LGA }) => ({ LGA }));

console.table(lgaArray);

提供视觉帮助的屏幕截图:

lga map array