我的网络服务中有这种列表。我想消除用户名重复:
Mylist = [{
"username": "Plr1",
"is_online": true,
"email": null,
"message": null,
"direction": 1,
"image_url": ""
}, {
"username": "plr2",
"is_online": false,
"email": "",
"message": null,
"direction": 1,
"image_url": ""
}, {
"username": "plr1",
"is_online": false,
"email": "",
"message": null,
"direction": 1,
"image_url": null
}];
是否有允许我删除重复值(其中一个元素=Plr1)的函数?
最佳答案
您可以使用 Array.filter
var Mylist = [{"username":"Plr1","is_online":true,"email":null,"message":null,"direction":1,"image_url":""},{"username":"plr2","is_online":false,"email":"","message":null,"direction":1,"image_url":""},{"username":"plr1","is_online":false,"email":"","message":null,"direction":1,"image_url":null} ];
var keys = [];
var newList = Mylist.filter(
function(x){
var val = x.username.toLowerCase();
if (!keys[val]) {
keys[val] = true;
return true;
}
return false;
}
);
keys = null;
console.log(newList);
它不适用于开箱即用的旧浏览器。如果您查看我在上面发布的链接,就会发现有一个 pollyfill 可以使它们正常工作。
关于javascript - 如何从列表中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16357312/