问题:如何使用 ReactJS 通过不同的键“分组”来重新格式化此 JSON 数组?
我有一个 JSON 数组:
[
{Product: "Shoes", Sold: 5, Bought : 0, Reversed : 2} ,
{Product: "Table", Sold: 2, Bought : 0, Reserved : 4}
]
原因是我正在使用的数据类型,并且在意识到我需要以不同的方式可视化这些数据时(由于我正在使用的图形包之一),我需要将这些数据构造为:
[
{
Status: "Sold",
Shoes : 5,
Table : 2
} ,
{
Status: "Bought",
Shoes : 0,
Table : 0
} ,
{
Status: "Reserved",
Shoes : 2,
Table : 4
}
]
因此,我将数据分组为除 Product 之外的键,然后是 Product,其值是 Product,它是“状态”。
坦白说,我完全不知道该怎么做,因为我认为生成它所需的代码会非常复杂,所以我很愿意知道这是否是太多的工作。
最佳答案
const data = [
{
Product: "Shoes",
Sold: 5,
Bought : 0,
Reserved : 2
} , {
Product: "Table",
Sold: 2,
Bought : 0,
Reserved : 4
}
];
let resultData = [];
Object.keys(data[0]).forEach((key, idx) => {
if (idx !== 0) {
let resultUnit = {
Status: key,
};
data.forEach(item => {
return resultUnit = {
...resultUnit,
[item.Product]: item[key],
}
})
resultData.push(resultUnit);
}
})
console.log(resultData);
// 0: {Status: "Sold", Shoes: 5, Table: 2}
// 1: {Status: "Bought", Shoes: 0, Table: 0}
// 2: {Status: "Reserved", Shoes: 2, Table: 4}
关于javascript - 如何根据不同的键将 JSON 数组重新格式化为另一种格式 "grouping",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59384059/