gpt4 book ai didi

javascript - 如何从 JavaScript 数组中删除重复对象

转载 作者:可可西里 更新时间:2023-11-01 02:01:09 25 4
gpt4 key购买 nike

这是我的代码

var studentsList = [
{"Id": "101", "name": "siva"},
{"Id": "101", "name": "siva"},
{"Id": "102", "name": "hari"},
{"Id": "103", "name": "rajesh"},
{"Id": "103", "name": "rajesh"},
{"Id": "104", "name": "ramesh"},
];

function arrUnique(arr) {
var cleaned = [];
studentsList.forEach(function(itm) {
var unique = true;
cleaned.forEach(function(itm2) {
if (_.isEqual(itm, itm2)) unique = false;
});
if (unique) cleaned.push(itm);
});
return cleaned;
}

var uniqueStandards = arrUnique(studentsList);

document.body.innerHTML = '<pre>' + JSON.stringify(uniqueStandards, null, 4) + '</pre>';

输出

[
{
"Id": "101",
"name": "siva"
},
{
"Id": "102",
"name": "hari"
},
{
"Id": "103",
"name": "rajesh"
},
{
"Id": "104",
"name": "ramesh"
}
]

在上面的代码中,我从 JavaScript 数组中获得了唯一的对象,但我想删除重复的对象。所以我想从数组中获取没有重复的对象,输出就像 [ { "编号": "102", “名称”:“哈里” }, { "编号": "104", “名称”:“拉梅什” } ]

最佳答案

检查这个

    var uniqueStandards = UniqueArraybyId(studentsList ,"id");

function UniqueArraybyId(collection, keyname) {
var output = [],
keys = [];

angular.forEach(collection, function(item) {
var key = item[keyname];
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return output;
};

关于javascript - 如何从 JavaScript 数组中删除重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32432938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com