如何从对象数组中查找并删除所有重复的对象

问题描述 投票:0回答:2

我收到以下响应,我想根据 lineId 和状态删除所有重复对象。 我正在尝试在下面的响应中找到所有具有新状态的重复项。

在下面的示例中,我想删除那些 lineId 相同但 status 为 New 的对象。

我尝试了下面的代码,但无法过滤预期的结果。

我很感谢对此的任何帮助。

const response = [
    {       
        "line": "Line 2",
        "lineId": "R_X002_WC02",        
        "status": "New"
    },
    {        
        "line": "Line 3",
        "lineId": "R_X002_WC03",
        "status": "New"
    },
    {       
        "line": "Line 2",
        "lineId": "R_X002_WC02",        
        "status": "Submitted"
    },
    {        
        "line": "Line 4",
        "lineId": "R_X002_WC04",
        "status": "New"
    },
    {        
        "line": "Line 4",
        "lineId": "R_X002_WC04",
        "status": "Submitted"
    }
];

以下是我的预期输出

const ExpectedOutput = [    
    {        
        "line": "Line 3",
        "lineId": "R_X002_WC03",
        "status": "New"
    },
    {       
        "line": "Line 2",
        "lineId": "R_X002_WC02",        
        "status": "Submitted"
    },
    {        
        "line": "Line 4",
        "lineId": "R_X002_WC04",
        "status": "Submitted"
    }
];

我尝试了下面的代码

var finalarr = [];
response.forEach((item) => {
        response.filter(i => i.lineId === item.lineId).length > 1
        finalarr.push(item);
      });
javascript typescript unique
2个回答
0
投票

const unique = new Set();
const finalarr = response.filter(item => {
    if (unique.has(item.lineId)) {
        return false; 
    } else {
        unique.add(item.lineId);
        return true;
    }
});
试试这个,它会根据你想要的效果工作


0
投票

一个好的方法是将此数组转换为一个新对象,其中键是对象的键,值可以是对象本身。这将消除任何重复项

var finalarr = {};
response.forEach((item) => {
        if(!finalarr[i.lineId] {
            finalarr[i.lineId] = i;
        }
    
      });

© www.soinside.com 2019 - 2024. All rights reserved.