从数组

时间:2016-12-26 07:30:35

标签: javascript angularjs

我有以下数组

var x = [
  '{"id":"item1","val":"Items"}',
  '{"id":"item1","val":"Items"}',
  '{"id":"item2","val":"Items"}',
  '{"id":"item2","val":"Items"}',
  '{"id":"item3","val":"Items"}',
  '{"id":"item2","val":"Items"}'
];

我希望通过id键创建唯一数组,如下所示:

[
  '{"id":"item1","val":"Items"}',
  '{"id":"item2","val":"Items"}',
  '{"id":"item3","val":"Items"}'
];

3 个答案:

答案 0 :(得分:2)

您可以使用 array.filter

var x = [
  '{"id":"item1","val":"Items"}',
  '{"id":"item1","val":"Items"}',
  '{"id":"item2","val":"Items"}',
  '{"id":"item2","val":"Items"}',
  '{"id":"item3","val":"Items"}',
  '{"id":"item2","val":"Items"}'
];

var unique = x.filter(function(elem, index, self) {
    return index == self.indexOf(elem);
})

console.log(unique);

答案 1 :(得分:0)

如果你可以使用jQuery:

var obj = {};
$.each(x,function(index,val){
 var temp = JSON.parse(val);
 obj[temp.id] = val;
})

var tempArray = [];

for(var i in obj){
tempArray.push(obj[i])
}

console.log(tempArray);

答案 2 :(得分:0)

ES6已于一年半前正式发布,为什么不尝试一下呢?

var unique = [...new Set(x)]

Set删除重复项...以在可迭代中传播成员。