特别声明:本文为原创,可自由转载、引用,但需署名作者且注明文章出处,如有侵权请联系!
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 }
]
文章来源:
zyglz
版权声明:本文为原创,可自由转载、引用,但需署名作者且注明文章出处,如有侵权请联系!
评论列表 (已有0条评论)
消灭零回复