这是我在 jquery 中的数组,其中包含重复的对象/元素:
[{
"name": "hello",
"label": "world"
}, {
"name": "abc",
"label": "xyz"
}, {
"name": "hello",
"label": "world"
}]
Run Code Online (Sandbox Code Playgroud)
我正在使用下面的一段代码来删除重复的元素,但它不起作用,重复的元素没有被删除。
var result = [];
$.each(subservices, function (i, e) {
if ($.inArray(e, result) == -1)
result.push(e);
});
alert(JSON.stringify(result));
Run Code Online (Sandbox Code Playgroud)
函数$.inArray对于简单类型(例如数字或字符串)工作正常,但对于复杂类型它不会产生正确的结果,因为它试图通过引用进行匹配。inArray您可以使用函数搜索数组,而不是在循环中使用grep:
var subservices = [{
"name": "hello",
"label": "world"
}, {
"name": "abc",
"label": "xyz"
}, {
"name": "hello",
"label": "world"
}
];
var result = [];
$.each(subservices, function (i, e) {
var matchingItems = $.grep(result, function (item) {
return item.name === e.name && item.label === e.label;
});
if (matchingItems.length === 0){
result.push(e);
}
});
//displays result [{"name":"hello","label":"world"},{"name":"abc","label":"xyz"}]
alert(JSON.stringify(result));
Run Code Online (Sandbox Code Playgroud)
这是一个有效的jsFiddle
| 归档时间: |
|
| 查看次数: |
9955 次 |
| 最近记录: |