如何使 JSON 数组唯一

How to make a JSON array unique

本文关键字:唯一 数组 JSON 何使      更新时间:2023-09-26

可能的重复项:
数组唯一值
使用 jQuery 从 JSON 数组获取唯一结果

我有一个这样的 JSON 字符串

[
 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"}
]

此 JSON 数组中有重复值。我怎样才能像这样使这个 JSON 数组独一无二

[
 Object { id="38",product="foo"},
 Object { id="39",product="bar"},
 Object { id="40",product="hello"}
]

.我正在寻找一个使用较少迭代的建议, 在这种情况下,Jquery $.inArray不起作用。

欢迎建议使用任何第三方库。

您可以使用下划线的 uniq。

在您的情况下,您需要提供一个迭代器来提取"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);

检查以下 SO 问题中的解决方案:

使用 jQuery 从 JSON 数组获取唯一结果

您必须遍历数组并创建一个包含唯一值的新数组。

您可能必须循环删除重复项。如果存储的项目如您所建议的那样有序,则只需执行一个简单的循环:

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

您可以自己轻松编写代码。从我的头顶上想到了这一点。

var filtered = $.map(originalArray, function(item) {
    if (filtered.indexOf(item) <= 0) {
        return item;
    }
});

或者建议专门针对手头情况的更有效的算法:

var helper = {};
var filtered = $.map(originalArray, function(val) {
    var id = val.id;
    if (!filtered[id]) {
        helper[id] = val;
        return val;
    }
});
helper = null;