具有以下格式的 JSON:
[{
name: "A",
country: "X",
countryID: "02",
value: 15
},
{
name: "A",
country: "Y",
countryID: "01",
value: 25
},
{
name: "B",
country: "X",
countryID: "02",
value: 35
},
{
name: "B",
country: "Y",
countryID: "01",
value: 45
}
]
如何在 Javascript 中按 name
、country
和 countryID
组合对象以获得以下 JSON 输出?
[{
country: "Y",
countryID: "01",
valueA: 25,
valueB: 45
},
{
country: "X",
countryID: "02",
valueA: 15,
valueB: 35
}
]
最佳答案
使用Array.prototype.reduce
,您可以按country
和countryID
键值对对数组项进行分组,并将结果存储到生成的键的对象值如下。
const input = [{
name: "A",
country: "X",
countryID: "02",
value: 15
},
{
name: "A",
country: "Y",
countryID: "01",
value: 25
},
{
name: "B",
country: "X",
countryID: "02",
value: 35
},
{
name: "B",
country: "Y",
countryID: "01",
value: 45
}
];
const groupBy = input.reduce((acc, cur) => {
const key = `${cur.country}_${cur.countryID}`;
acc[key] ? acc[key][`value${cur.name}`] = cur.value : acc[key] = {
country: cur.country,
countryID: cur.countryID,
['value' + cur.name]: cur.value
};
return acc;
}, {});
const output = Object.values(groupBy);
console.log(output);
关于javascript - 使用 javascript 将对象合并到 json 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64684490/