我有以下数组
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"}'
];
答案 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)