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

标签 javascript json

这是当前的 JSON 文件:

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

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

最佳答案

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

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

为了从 Objects 数组中过滤掉重复的名称,我们使用 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' } ]

关于javascript - 从 JavaScript 中的 JSON 文件中删除重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22614275/

相关文章:

javascript - 如何使滚动菜单中的菜单和 Logo 颜色变化?

javascript - 在 JQuery 中调用 Web 服务并将返回的 Json 分配给 JS 变量

javascript - 如果 JSON 响应上的图像 src 为空如何设置默认本地镜像

json - 如何使用 awk/sed 在两行之间添加新的文本行? (在文件中)

json - Golang net/http 请求 Body 总是空的

javascript - 将微调器添加到 jquery 提交的输入

javascript - 在javascript中定位数组中的最后一项

python - 在 python 中编辑 CSV 文件,该文件从 python 中的另一个 json 文件读取值

javascript - React Native "run-ios"意外的 token

javascript - 为什么以下 JavaScript 代码无效?