gpt4 book ai didi

javascript - 如何从列表中删除重复项

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:36:02 25 4
gpt4 key购买 nike

我的网络服务中有这种列表。我想消除用户名重复:

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/

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