小编典典

从json数据中删除重复值[duplicate]

json

我有一个像这样的json数据:

{
  "_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" 
}

从中,我必须使用删除一个重复的条目id:27,与情况相同,id:23 结果json如下:

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

怎么可能


阅读 540

收藏
2020-07-27

共1个答案

小编典典

[**Fiddle Demo**](http://jsfiddle.net/cse_tushar/wtXx4/)

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's all values
    }
});
console.log(collection); //you can access it values like collection[index].keyName
console.log(arr);
2020-07-27