json对象根据指定字段去重
2019-07-15 本文已影响0人
路尔轩
function filterByName(data, Name) { //data是json对象,Name是根据什么字段去重
var map = {},
dest = [];
for (var i = 0; i < data.length; i++) {
var ai = data[i];
if (i == 0) {
dest.push(ai);
} else {
var filterData = dest.filter(function (e) {
return e[Name] == ai[Name];
})
if (filterData.length == 0) {
dest.push(ai);
}
}
}
return dest;
}
let json1 = [{
"aa": "aa1",
"bb": "bb",
"image": "60",
"publish_time": 1562057299
}, {
"aa": "aa2",
"bb": "bb",
"image": "61",
"publish_time": 1562057309
}, {
"aa": "aa3",
"bb": "bb",
"image": "61",
"publish_time": 1562057309
}, {
"aa": "aa4",
"bb": "bb",
"image": "61",
"publish_time": 1562057309
}]
filterByName(json1,'image')
// 调用结果
[{
"aa": "aa1",
"bb": "bb",
"image": "60",
"publish_time": 1562057299
}, {
"aa": "aa2",
"bb": "bb",
"image": "61",
"publish_time": 1562057309
}]