gpt4 book ai didi

javascript - 通过计算将对象数组转换为数组

转载 作者:行者123 更新时间:2023-11-30 19:50:57 25 4
gpt4 key购买 nike

我正在使用以下对象数组并尝试将其转换为数组:

const data = [
{
count: 3,
userName: "Paul Crewe",
value: "Activity Type",
},
{
count: 1,
userName: "Nate Scarborough",
value: "Activity Type",
},
{
count: 1,
userName: "Nate Scarborough",
value: "Another Activity Type",
},
{
count: 1,
userName: "Paul Crewe",
value: "Another Activity Type",
},
];

预期结果:

const outcome = [
['userName', 'Paul Crewe', 'Nate Scarborough'],
['Activity Type', 3, 1],
['Another Activity Type', 1, 1]
];

结果数组获取数据并使用 userName 键创建第一个数组元素,后跟 value 格式,count 为每个额外的数组元素。例如,

['userName', 'Paul Crewe', 'Nate Scarborough'],
[{value}, {count for Paul Crewe}, {count for Nate Scarborough} ],

我觉得使用reduce 是合适的并且已经开始:

data.reduce((a, c) => {
a[c.userName] = { value: c.value, count: c.count };
a[c.userName].count += c.count;
return a;
}, {});

但这会导致不希望的结果,例如:

{
Nate Scarborough: {value: "Another Activity Type", count: 2},
Paul Crewe: {value: "Another Activity Type", count: 2},
}

最佳答案

您可以从键 userName 开始,然后根据需要构建新的值行。它适用于任意数量的值。

这个解决方案可以返回一个稀疏数组。如果不需要,则需要使用默认零映射内部数组。

const
data = [{ count: 3, userName: "Paul Crewe", value: "Activity Type" }, { count: 1, userName: "Nate Scarborough", value: "Activity Type" }, { count: 1, userName: "Nate Scarborough", value: "Another Activity Type" }, { count: 1, userName: "Paul Crewe", value: "Another Activity Type" }],
result = data.reduce((r, o) => {
var vIndex = r.findIndex(([v]) => v === o.value),
index = r[0].indexOf(o[r[0][0]]);

if (vIndex < 0) {
vIndex += r.push([o.value]);
}
if (index < 0) {
index += r[0].push(o[r[0][0]]);
}
r[vIndex][index] = (r[vIndex][index] || 0) + o.count;
return r;
}, [['userName']]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 通过计算将对象数组转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54480165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com