如何从对象数组中删除重复的名称

时间:2016-09-28 07:06:27

标签: javascript

var arr = [
    {level:0,name:"greg"},
    {level:0,name:"Math"},
    {level:0,name:"greg"}
];

我尝试了以下内容:

function removeDuplicates:(dataObject){
    self.dataObjectArr = Object.keys(dataObject).map(function(key){
        return dataObject[key];
    });

    for(var i= 0; i < self.dataObjectArr.length; i++ ){
        self.dataObjectArr[i]['name'] = self.dataObjectArr[i];

        self.uniqArr = new Array();
        for(var key in self.dataObjectArr){
            self.uniqArr.push(self.dataObjectArr[key]);
        }
    }
    self.uniqObject = DataMixin.toObject(self.uniqArr);
    return self.uniqObject;
}

但是我得到错误说:Uncaught TypeError:将循环结构转换为JSON。

5 个答案:

答案 0 :(得分:2)

这是一个通用的&#34; uniquify&#34;功能:

&#13;
&#13;
function uniqBy(a, key) {
    var seen = new Set();
    return a.filter(item => {
        var k = key(item);
        return !seen.has(k) && seen.add(k)
    });
}

///

var arr = [
    {level:0,name:"greg"},
    {level:0,name:"greg"},
    {level:0,name:"joe"},
    {level:0,name:Math},
    {level:0,name:"greg"},
    {level:0,name:"greg"},
    {level:0,name:Math},
    {level:0,name:"greg"}
];

uniq = uniqBy(arr, x => x.name);
console.log(uniq);
&#13;
&#13;
&#13;

有关深入讨论,请参阅here

答案 1 :(得分:2)

您应该将name推送到数组或集合,并在下面检查相同的内容。

&#13;
&#13;
var arr = [{
  level: 0,
  name: "greg"
}, {
  level: 0,
  name: "Math"
}, {
  level: 0,
  name: "greg"
}]

function removeDuplicates(arr) {
  var temp = []
  return arr.filter(function(el) {
    if (temp.indexOf(el.name) < 0) {
      temp.push(el.name)
      return true
    }
  })
}

console.log(removeDuplicates(arr))
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我相信你有一个语法错误“removeDuplicates:(dataObject){...”

应该没有“:”&gt;&gt; “removeDuplicates(dataObject){...”  “

你可以试试这个:

function removeDuplicates(arr){
    var match={}, newArr=[];
    for(var i in arr){ if(!match[arr[i].name]){ match[arr[i].name]=1; var newArr=i; } }
    return newArr;
}

arr = removeDuplicates(arr);

答案 3 :(得分:0)

您可以使用$.unique()$.map()$.grep()

var arr = [
  {level:0,name:"greg"},
  {level:0,name:"Math"},
  {level:0,name:"greg"}
];

var res = $.map($.unique($.map(arr, el => el.name)), name => 
            $.grep(arr, el => el.name === name)[0]);

jsfiddle https://jsfiddle.net/4tex8xhy/3

答案 4 :(得分:0)

或者您可以使用下划线或lodash(https://lodash.com/docs/4.16.2)这样的库。 Lodash示例:

var arr = [
    {level:0,name:"greg"},
    {level:0,name:"Math"},
    {level:0,name:"greg"}
];

var result = _.map(_.keyBy(arr,'name'));

//result will contain
//[
//   {
//    "level": 0,
//    "name": "greg"
//    },
//    {
//    "level": 0,
//    "name": "Math"
//    }
//]

OFC。在这些任务中总是要考虑的一件事是,你想要做的是什么:修改现有阵列,或者重新获得一个新阵列。此示例返回一个新数组。