Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

javascript - 从JavaScript中的对象数组中删除重复项(Remove duplicates from an array of objects in JavaScript)

I have an object that contains an array of objects.

(我有一个包含对象数组的对象。)

things = new Object();

things.thing = new Array();

things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});

I'm wondering what is the best method to remove duplicate objects from an array.

(我想知道什么是从数组中删除重复对象的最佳方法。)

So for example, things.thing would become...

(举例来说,事物……东西将变成……)

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}
  ask by Travis translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about with some es6 magic?

(使用一些es6魔术怎么样?)

things.thing = things.thing.filter((thing, index, self) =>
  index === self.findIndex((t) => (
    t.place === thing.place && t.name === thing.name
  ))
)

Reference URL

(参考网址)

A more generic solution would be:

(更通用的解决方案是:)

const uniqueArray = things.thing.filter((thing, index) => {
  const _thing = JSON.stringify(thing);
  return index === things.thing.findIndex(obj => {
    return JSON.stringify(obj) === _thing;
  });
});

Stackblitz Example

(Stackblitz示例)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...