gpt4 book ai didi

javascript - 如何按对象属性对数组进行分组

转载 作者:行者123 更新时间:2023-12-01 01:01:30 25 4
gpt4 key购买 nike

我有数组重复数据。我需要组数组 一起来

const data = [
{ id: 1, name: "john", cardId: "0001" },
{ id: 1, name: "john", cardId: "0001" },
{ id: 1, name: "john", cardId: "0002" },
{ id: 2, name: "poul", cardId: "0003" },
{ id: 2, name: "poul", cardId: "0003" },
{ id: 2, name: "poul", cardId: "0004" }
];

我需要对重复数据进行分组。走到一起并且只有一个像这样>>

const res = [ 
{ id: 1, name: "john", card: [{ cardId: "0001" }, { cardId: "0002"} ] },
{ id: 2, name: "poul", card: [{ cardId: "0003" }, { cardId: "0004"} ] }
];

非常感谢您的帮助。

最佳答案

var data = [
{ id: 1, name: "john", cardId: "0001" },
{ id: 1, name: "john", cardId: "0001" },
{ id: 1, name: "john", cardId: "0002" },
{ id: 2, name: "poul", cardId: "0003" },
{ id: 2, name: "poul", cardId: "0003" },
{ id: 2, name: "poul", cardId: "0004" }
];

var res = [];
data.forEach(a => {
var searchResultInRes = res.find(x => x.id == a.id);
if (searchResultInRes) {
if (!searchResultInRes.card.some(x => x.cardId == a.cardId)) {
searchResultInRes.card.push({ cardId: a.cardId });
}
} else {
res.push({ id: a.id, name: a.name, card: [{ cardId: a.cardId }] });
}
});

console.log(res);

关于javascript - 如何按对象属性对数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56026967/

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