2

如果数据是这样的: -

const dis ={
    "data":[
        {
            "Hazard_type": ["Tornado","Hurricane"],
            "County": "Anderson",
            "State": "TX",
            "FIPS_code": 48001,
            "Longitude": -95.687072,
            "Latitude": 31.776143,
            "Property_Damage": 10000000,
            "Crop_Damage": 0
        },
        {
            "Hazard_type": ["Hurricane"],
            "County": "Anderson",
            "State": "TX",
            "FIPS_code": 48001,
            "Longitude": -95.687072,
            "Latitude": 31.776143,
            "Property_Damage": 4914933.84,
            "Crop_Damage": 0
        },
    ]
}

我想创建另一个 json 数组,该数组对 Hazard 类型中的每个唯一标签具有聚合损坏。这里应该采用什么方法?(对 Javascript 非常陌生)

4

2 回答 2

0

这是使用Array.filterArray.reduce完成任务的一种方法。

请注意,我将 Crop_Damage 的值从零更改为 3 和 1,以使代码的工作更加明显。

const dis ={
    "data":[
        {
            "Hazard_type": ["Tornado","Hurricane"],
            "County": "Anderson",
            "State": "TX",
            "FIPS_code": 48001,
            "Longitude": -95.687072,
            "Latitude": 31.776143,
            "Property_Damage": 10000000,
            "Crop_Damage": 1
        },
        {
            "Hazard_type": ["Hurricane"],
            "County": "Anderson",
            "State": "TX",
            "FIPS_code": 48001,
            "Longitude": -95.687072,
            "Latitude": 31.776143,
            "Property_Damage": 4914933.84,
            "Crop_Damage": 3
        },
    ]
};

const removeDuplicates = (key, index, array) => {
  return array.lastIndexOf(key) === index;
};

const distinctHazards = dis.data.map(row => row.Hazard_type).flat().filter(removeDuplicates);

/*
 * Array.filter() ensures we only examine the subset of the array having to do with one Hazard at a time
 * Array.reduce() is an accumulator that simply sums the fields (Crop_Damage) up. 
*/
const scores = distinctHazards.map(hazard => {
    const damages = dis.data.filter(row => {
        return row.Hazard_type.includes(hazard);
    });
    return {hazard, damages: damages.map(row => row.Crop_Damage).reduce((a,b) => {
        return Number(a) + Number(b);
    })};
});

console.log(scores);

于 2021-04-12T23:17:44.597 回答
0

您可以使用 Array.map 函数。在此处查看此函数的定义:

例如,您可以将其用于:

const rows = [
  { name: "Name 1", price: 1.0, tax, 0.5 }, 
  { name: "Name 2"price: 2.0, tax, 0.5 }
];
const newRows = rows.map(row => {
   return {
      ..row,
      totalPrice: row.price + tax,
   };
});

所以在这个 newRows 之后是这样的:

[
  { name: "Name 1", price: 1.0, tax, 0.5, totalPrice: 1.5 }, 
  { name: "Name 2"price: 2.0, tax, 0.5, totalPrice: 2.5 }
]
于 2021-04-12T19:06:37.313 回答