在JavaScript中从JSON文件中删除重复的对象

时间:2014-03-24 15:53:28

标签: javascript json

这是当前的JSON文件:

[{
    "name": "Peter",
    "age": 30,
    "hair color": "brown"
}, {
    "name": "Steve",
    "age": 55,
    "hair color": "blonde"
}, {
    "name": "Steve",
    "age": 55,
    "hair color": "blonde"
}]

我想从列表中删除重复的Steve个人。如何创建一个新的JSON来检查对象的名称是否匹配并删除JavaScript中的任何重复项?

5 个答案:

答案 0 :(得分:8)

您必须将JSON数据加载到程序中并使用JSON.parse解析它,就像这样

var array = JSON.parse(content.toString())

要从对象数组中筛选出重复的名称,我们使用Array.prototype.filter函数。您可以将名称存储在对象中,下次出现相同的名称时,我们只需将其从结果中过滤掉。

var seenNames = {};

array = array.filter(function(currentObject) {
    if (currentObject.name in seenNames) {
        return false;
    } else {
        seenNames[currentObject.name] = true;
        return true;
    }
});

console.log(array);
# [ { name: 'Peter', age: 30, 'hair color': 'brown' },
#   { name: 'Steve', age: 55, 'hair color': 'blonde' } ]

答案 1 :(得分:1)

使用Underscore.jsuniq功能:

_.uniq(array, false, function (item) { return item.name; })

答案 2 :(得分:0)

循环,检查,拼接,重复:

var distinctValues = {};
for (var i = 0; i < data.length; i++) {
    if (distinctValues.hasOwnProperty(data[i].name]) {
        //already has it
        data.splice(i, 1);
        i--;
    } else {
        distinctValues[data[i].name] = true;
    }
}

答案 3 :(得分:0)

var data = [{
    "name": "Peter",
    "age": 30,
    "hair color": "brown"
}, {
    "name": "Steve",
    "age": 55,
    "hair color": "blonde"
}, {
    "name": "Steve",
    "age": 55,
    "hair color": "blonde"
}]
 data = this.data.filter((obj, pos, arr) => {
            return arr.map(mapObj =>
                  mapObj.name).indexOf(obj.name) == pos;
            });
          console.log(data);

答案 4 :(得分:-3)

来自CLI的Python one-liner:

cat file_with_duplicates.json | python2 -c 'import sys; import json; sys.stdout.write(json.dumps(reduce(lambda x, y: x + [y] if y not in x else x, json.loads(sys.stdin.read()), [])))' > unique_items.txt