我收到以下响应,我想根据 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);
});
const unique = new Set();
const finalarr = response.filter(item => {
if (unique.has(item.lineId)) {
return false;
} else {
unique.add(item.lineId);
return true;
}
});
一个好的方法是将此数组转换为一个新对象,其中键是对象的键,值可以是对象本身。这将消除任何重复项
var finalarr = {};
response.forEach((item) => {
if(!finalarr[i.lineId] {
finalarr[i.lineId] = i;
}
});