在js中,如何从对象数组中删除掉重复的对象?

coding2live 2021-01-20 15:52:53 101

我创建了下面的对象:

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

有什么办法可以去除数组中重复的对象元素吗?

我想得到下面的结果:

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}

以下答案仅供参考

下面的方法虽然原始,但是可行:

var obj = {};

for ( var i=0, len=things.thing.length; i < len; i++ )
    obj[things.thing[i]['place']] = things.thing[i];

things.thing = new Array();
for ( var key in obj )
    things.thing.push(obj[key]);