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

时间:2019-05-07 16:34:35

标签: javascript arrays

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

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"} ] } 
];

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您可以使用reduce根据name对项目进行分组。创建一个名为card的{​​{3}}属性,以便为每个cardId获得唯一的name。然后遍历集合以创建输出

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 merged = data.reduce((r, { id, name, cardId }) => {
  r[name] = r[name] || { id, name, card: new Set };
  r[name].card.add(cardId)
  return r;
}, {})

const output = Object.values(merged).map(({ card, id, name }) => 
        ({ id, name, card: [...card].map(cardID => ({ cardID })) }) )
      
console.log(output)

答案 2 :(得分:0)

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'}];

let grouped = data.reduce((acc, {id, name, cardId}) => {
  let d = acc.find(d => d.id === id);
  if (!d)
    acc.push({id, name, card: [cardId]});
  else if (!d.card.includes(cardId))
    d.card.push(cardId);
  return acc;
}, []);

console.log(grouped);