Remove duplicate values ​​from json data

I have json data:

{
  "_id": ObjectId("5306e7fd80b1027ad2653db4"),
  "testada": "ecom",
  "id": "27" 

} {
  "_id": ObjectId("5306e81880b1027ad2653db5"),
  "testada": "alorta",
  "id": "27" 
} {
  "_id": ObjectId("5306e81880b1027ad2653db6"),
  "testada": "france24",
  "id": "23" 
}
{
  "_id": ObjectId("5306e81880b1027ad2653db6"),
  "testada": "seloger",
  "id": "23" 
}

From this I have to remove one duplicate entry with id:27, just as in the case id:23 my result jsonlooks like this:

{
  "_id": ObjectId("5306e81880b1027ad2653db5"),
  "testada": "alorta",
  "id": "27" 
} {
  "_id": ObjectId("5306e81880b1027ad2653db6"),
  "testada": "france24",
  "id": "23" 
}

how is this possible

+3
source share
2 answers

var arr = [], //to collect id values 
    collection = []; //collect unique object

$.each(json_all, function (index, value) {
    if ($.inArray(value.id, arr) == -1) { //check if id value not exits than add it
        arr.push(value.id);//push id value in arr
        collection.push(value); //put object in collection to access it all values
    }
});
console.log(collection); //you can access it values like collection[index].keyName
console.log(arr);
+7
source

You can get a collection of objects from a JSON string using JSON.parse ("jsonstring"), in which you can iterate and get non-duplicate elements

var objColl = JSON.parse("JSON string");
var categories = [];

$.each(objColl, function(index, value) {
    if ($.inArray(value.category, categories)==-1) {
        categories.push(value.category);
    }
});
+1
source

All Articles