gpt4 book ai didi

javascript - 计算数组中对象中两个键的出现次数

转载 作者:行者123 更新时间:2023-11-29 10:58:56 24 4
gpt4 key购买 nike

我有以下包含对象的数组,并使用以下代码创建带有键“id”的计数:

var arr=[
{ id: 123,
title: "name1",
status: "FAILED"
},
{
id: 123,
title: "name1",
status: "PASSED"
},
{
id: 123,
title: "name1",
status: "PASSED"
},
{
id: 123,
title: "name1",
status: "PASSED"
},
{
id: 1234,
title: "name2",
status: "FAILED"
},
{
id: 1234,
title: "name2",
status: "PASSED"
}

];


const test =arr.reduce((tally, item) => {

if (!tally[item.id]) {
tally[item.id] = 1;
} else {
tally[item.id] = tally[item.id] + 1;
}
return tally;
}, {});

console.log(test);

现在我想做的是修改计数以考虑关键状态,因此结果将类似于:

[
{id:123, status:"PASSED", tally:3},
{id:123, status:"FAILED", tally:1},
{id:1234, status:"PASSED", tally:1},
{id:1234, status:"FAILED", tally:1}
]

有什么想法吗?谢谢!

最佳答案

把key做成item.id + item.status,然后就是简单的赋值

const res = Object.values(arr.reduce((a, b) => {
a[b.id + b.status] = Object.assign(b, {tally: (a[b.id + b.status] || {tally: 0}).tally + 1});
return a;
}, {}));

console.log(res);
<script>
const arr=[
{ id: 123,
title: "name1",
status: "FAILED"
},
{
id: 123,
title: "name1",
status: "PASSED"
},
{
id: 123,
title: "name1",
status: "PASSED"
},
{
id: 123,
title: "name1",
status: "PASSED"
},
{
id: 1234,
title: "name2",
status: "FAILED"
},
{
id: 1234,
title: "name2",
status: "PASSED"
}

];
</script>

关于javascript - 计算数组中对象中两个键的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51153174/

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