资源管理站

JS删除JSON数组中相同重复的元素或者对象

zyglz 650 0

特别声明:本文为原创,可自由转载、引用,但需署名作者且注明文章出处,如有侵权请联系!

JS删除JSON数组中相同重复的元素或者对象

var tec=[
        {"name":"li","age":18},
        {"name":"zhang","age":17},
        {"name":"zhao","age":20},
        {"name":"wang","age":30},
        {"name":"zhao","age":20},        
    ];

alert(tec.length);//输出:5
new_tec=deteleObject(tec)
alert(new_tec.length);//输出:4

console.log(JSON.stringify(new_tec, null, "\t"));

function deteleObject(obj) {
    var uniques=[];
    var stringify = {};
    for(var i=0; i<obj.length; i++) {
        var keys = Object.keys(obj[i]);
        var str='';
        for(var j=0; j < keys.length; j ++) {
            str += JSON.stringify(keys[j]);
            str += JSON.stringify(obj[i][keys[j]]);
        }
        if(!stringify.hasOwnProperty(str)) {
            uniques.push(obj[i]);
            stringify[str]=true;
        }
    }
    return uniques;
}

得到的结果为:

[
{ "name": "li", "age": 18 }, 
{ "name": "zhang", "age": 17 },
{ "name": "zhao", "age": 20 }, 
{ "name": "wang", "age": 30 }
]

评论列表 (已有0条评论)

消灭零回复

发表评论 (已有0条评论)

icon_lol.gif2016zhh.gif2016fendou.gif2016lengh.gificon_exclaim.gif2016gg.gif2016yhh.gificon_cry.gif2016bs.gif2016qd.gif2016bz.gificon_eek.gif2016ka.gif2016zhem.gificon_confused.gif2016qq.gif2016db.gif2016jk.gif2016tuu.gif2016zk.gif2016kk.gificon_neutral.gif