我正在处理一组对象,如:
const data = [
{type: "Liberator", style: "Moderately Logical"},
{type: "Protector", style: "Somewhat Passionate"},
{type: "Energizer", style: "Balanced"},
{type: "Observer", style: "Balanced"},
{type: "Protector", style: "Balanced"},
{type: "Liberator", style: "Moderately Logical"},
];我希望将数组减少为数组中所有项的汇总百分比。
例如,最高级别的“保护器”=6或33%中的2。对于每一个“保护者”,有一个“有点激情”的2种风格,另一种是“平衡”50%。
预期结果:
const result = [
{
type: "Liberator",
percent: "33%",
[{
style: "Moderately Logical",
percent: "100%",
}],
},
{
type: "Protector",
percent: "33%",
[{
style: "Somewhat Passionate",
percent: "50%",
},{
style: "Balanced",
percent: "50%",
}],
},
{
type: "Observer",
percent: "17%",
[{
style: "Balanced",
percent: "100%",
}],
},
{
type: "Energizer",
percent: "17%",
[{
style: "Moderately Logical",
percent: "100%",
}],
},
];我已经成功地获得了简化的原始数组,但现在不确定如何对每个条目进行计算:
data.filter((d, index, self) =>
index === self.findIndex(t => (
t.type === d.type && t.style === d.style
)),
);发布于 2018-12-18 21:17:39
您可以首先计算每种类型和样式的计数,然后计算它们的百分比:
const data = [
{type: "Liberator", style: "Moderately Logical"},
{type: "Protector", style: "Somewhat Passionate"},
{type: "Energizer", style: "Balanced"},
{type: "Observer", style: "Balanced"},
{type: "Protector", style: "Balanced"},
{type: "Liberator", style: "Moderately Logical"},
];
function toPercent(arr) {
const total = arr.reduce((a, c) => a + c.count, 0);
return arr.map(({count, ...props}) =>
({ ...props, percent: Math.round((count * 100) / total) + '%'}));
}
const counts = data.reduce((a, c) => {
a[c.type] = a[c.type] || {type: c.type, count: 0, styles: {}};
a[c.type].count++;
a[c.type].styles[c.style] = a[c.type].styles[c.style] || {style: c.style, count: 0};
a[c.type].styles[c.style].count++;
return a;
}, {});
const result = toPercent(Object.values(counts))
.map(({styles, ...props}) => ({ ...props, styles: toPercent(Object.values(styles))}));
console.log(result);
https://stackoverflow.com/questions/53840791
复制相似问题