从json数据中删除重复值

时间:2014-02-22 07:14:04

标签: jquery 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" 
}

如何可能

2 个答案:

答案 0 :(得分:7)

Fiddle Demo

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);

答案 1 :(得分:1)

您可以使用JSON.parse(“jsonstring”)从JSON字符串中获取对象集合,您可以在其中迭代并获取非重复项

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

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