我有数组重复数据。
我需要组数组

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);

09-16 06:00