我有一个关于 Wine 的数据集。对于每个 Wine 标签,我都有几个信息,如原产国、酿造的葡萄、是白 Wine 还是红 Wine 、评级等。我从 csv 中获取这些数据。最终,对于我正在构建的可视化,我需要一个类型的数据:Grape |白色或红色 |计数。我能够得到这样的数据:
count: 1
grape: (3) ["Pinot Noir", "Malbec", "Garnacha"]
type: "Red wine"
count: 1
grape: ["Pinot Noir"]
type: "Red wine"
count: 1
grape: ["Pinot Noir"]
type: "Red wine"
对于我数据集中的每个 Wine 标签。但是,我需要这样的数据:
count: 1
grape: "Pinot Noir"
type: "Red wine"
count: 1
grape: "Malbec"
type: "Red wine"
count: 1
grape: "Garnacha"
type: "Red wine"
count: 1
grape: "Pinot Noir"
type: "Red wine"
count: 1
grape: "Pinot Noir"
type: "Red wine"
以便稍后我可以简化为:
count: 3
grape: "Pinot Noir"
type: "Red wine"
count: 1
grape: "Malbec"
type: "Red wine"
count: 1
grape: "Garnacha"
type: "Red wine"
是否可以通过 javascript 做到这一点?
最佳答案
你可以试试下面的代码。
var data = [
{ count: 1, grape: ["Pinot Noir", "Malbec", "Garnacha"], type: "Red wine" },
{ count: 1, grape: ["Pinot Noir"], type: "Red wine" },
{ count: 1, grape: ["Pinot Noir"], type: "Red wine" }
];
var newData = [];
data.forEach(item => {
item.grape.forEach(g => {
var addedItem = newData.find(f => f.type == item.type && f.grape == g);
if (addedItem) {
addedItem.count += +item.count;
} else {
newData.push({
count: +item.count,
grape: g,
type: item.type
});
}
});
});
console.log('Result: ', newData);
编辑:可以通过以下方式更改代码以获得更好的性能。
var data = [
{ count: 1, grape: ["Pinot Noir", "Malbec", "Garnacha"], type: "Red wine" },
{ count: 1, grape: ["Pinot Noir"], type: "Red wine" },
{ count: 1, grape: ["Pinot Noir"], type: "Red wine" }
];
var counts = {};
data.forEach(item => {
item.grape.forEach(g => {
if (counts[item.type]) {
if (counts[item.type][g]) {
counts[item.type][g] += +item.count;
} else {
counts[item.type][g] = +item.count;
}
} else {
counts[item.type] = { [g]: item.count };
}
});
});
var newData = [];
Object.keys(counts).forEach(type => {
Object.keys(counts[type]).forEach(grape => {
newData.push({ count: counts[type][grape], grape: grape, type: type });
});
});
console.log('Result: ', newData);
关于javascript - 取消嵌套和减少javascript中的数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57155959/