Possible Duplicate:
Array unique values
Get unique results from JSON array using jQuery
Im having a JSON string like this
[
Object { id="38",product="foo"},
Object { id="38",product="foo"},
Object { id="38",product="foo"},
Object { id="39",product="bar"},
Object { id="40",product="hello"},
Object { id="40",product="hello"}
]
There are duplicate values in this JSON array..how can i make this JSON array unique like this
[
Object { id="38",product="foo"},
Object { id="39",product="bar"},
Object { id="40",product="hello"}
]
.Im looking for a suggestion that uses less iterations,
Jquery $.inArray
is not working in this case.
Suggestion to use any third party libraries are welcome.
Check the solution in the following SO question:
Get unique results from JSON array using jQuery
You'll have to iterate through your array and create a new array which contains unique values.
You can use underscore's uniq.
In your case, you need to provide an iterator to extract 'id':
array = _.uniq(array, true /* array already sorted */, function(item) {
return item.id;
});
// Assuming first that you had **_valid json_**
myList= [
{ "id":"38","product":"foo"},
{ "id":"38","product":"foo"},
{ "id":"38","product":"foo"},
{ "id":"39","product":"bar"},
{ "id":"40","product":"hello"},
{ "id":"40","product":"hello"}
];
// What you're essentially attempting to do is turn this **list of objects** into a **dictionary**.
var newDict = {}
for(var i=0; i<myList.length; i++) {
newDict[myList[i]['id']] = myList[i]['product'];
}
// `newDict` is now:
console.log(newDict);
You will probably have to loop through removing the duplicates. If the items stored are in order as you have suggested, it's a simple matter of a single loop:
function removeDuplicates(arrayIn) {
var arrayOut = [];
for (var a=0; a < arrayIn.length; a++) {
if (arrayOut[arrayOut.length-1] != arrayIn[a]) {
arrayOut.push(arrayIn[a]);
}
}
return arrayOut;
}
You can easily code this yourself. From the top of my head this comes to mind.
var filtered = $.map(originalArray, function(item) {
if (filtered.indexOf(item) <= 0) {
return item;
}
});
Or as suggested a more efficient algorithm specifically for the case at hand:
var helper = {};
var filtered = $.map(originalArray, function(val) {
var id = val.id;
if (!filtered[id]) {
helper[id] = val;
return val;
}
});
helper = null;
来源:https://stackoverflow.com/questions/11826302/how-to-make-a-json-array-unique