提问者:小点点

如何使用Javascript[duplicate]从具有多个参数的数组中删除重复项


我正在尝试格式化从csv文件创建的数组。在将其解析为正确的格式后,我需要一种方法来删除我在csv文件中遇到的重复项。

这是我拥有的数组的一个示例

[{
    "pccs": ["1ADA"],
    "markets": [{
        "origin": "LAX",
        "destination": "DFW"
    }, {
        "origin": "LAX",
        "destination": "IAH"
    }, {
        "origin": "LAX",
        "destination": "IAH"
    }, {
        "origin": "LAX",
        "destination": "IAH"
    }]
}, {
    "pccs": ["1ABA"],
    "markets": [{
        "origin": "LAX",
        "destination": "JFK"
    }]
}]

我试图将其格式化为仅为列表中的每个元素显示一个唯一集,以获得如下响应:

[{
    "pccs": ["1ADA"],
    "markets": [{
        "origin": "LAX",
        "destination": "DFW"
    }, {
        "origin": "LAX",
        "destination": "IAH"
    }]
}, {
    "pccs": ["1ABA"],
    "markets": [{
        "origin": "LAX",
        "destination": "JFK"
    }]
}]

我倾向于使用filter()函数,但不确定如何用对象列表实现它。我需要创建一个嵌套循环来访问每个元素吗?


共1个答案

匿名用户

可以使用every()创建一个助手函数来比较两个对象。然后在数组每个元素的市场上使用filter(),并移除所需元素。

注意:我使用了forEach,code将修改原始数组,因为我认为您需要修改原始数组。如果不是这样,请询问我,我将添加其他解决方案。

const arr = [{ "pccs": ["1ADA"], "markets": [{ "origin": "LAX", "destination": "DFW" }, { "origin": "LAX", "destination": "IAH" }, { "origin": "LAX", "destination": "IAH" }, { "origin": "LAX", "destination": "IAH" }] }, { "pccs": ["1ABA"], "markets": [{ "origin": "LAX", "destination": "JFK" }] }]

const compObjs = (obj1, obj2) => Object.keys(obj1).every(k => obj1[k] === obj2[k])
arr.forEach(x => {
  x.markets = x.markets.filter(a => x.markets.find(b => compObjs(b,a)) === a)
})
console.log(arr)