4

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

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)的功能?

4

3 回答 3

3

您可以使用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 可以使它们工作。

于 2013-05-03T11:06:28.247 回答
1

这将做你想要的(假设你正在寻找不区分大小写的用户名比较)。

编辑添加演示:http: //jsfiddle.net/vBZhR/

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

dedupe(Mylist);
function dedupe(list) {
    var usernames = {};
    for (var i in list) {
        if (usernames[list[i].username.toLowerCase()]) {
            list.splice(i, 1);
        } else {
            usernames[list[i].username.toLowerCase()] = true;
        }
    }
    return list;
}
于 2013-05-03T11:03:09.660 回答
1

演示:http: //jsfiddle.net/abc123/ZgYbB/

注意:最后一个 for 循环只是为了显示删除的项目以及数组中剩下的内容。

JS:

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

for (var i = 0; i < Mylist.length; i++) {
    for(var j = i + 1; j < Mylist.length; j++) {
        if(Mylist[i].username.toLowerCase() == Mylist[j].username.toLowerCase())
            Mylist.splice(j, 1);
    }
}

//Not needed just proof that items were removed.
for (var i = 0; i < Mylist.length; i++) {
   alert(Mylist[i].username);
}
于 2013-05-03T11:06:44.750 回答