美文网首页
json对象根据指定字段去重

json对象根据指定字段去重

作者: 路尔轩 | 来源:发表于2019-07-15 18:02 被阅读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
}]

相关文章

网友评论

      本文标题:json对象根据指定字段去重

      本文链接:https://www.haomeiwen.com/subject/xkrokctx.html