为什么param
生成的对象过多,而最多应有4个对象。它应与dbData.Items[dbItemIndex].Id == lineId
之间的ID匹配,并将元数据存储在param
中,包括dbData
数组索引。
const dbData = {
Items: [
{Id: 111},
{Id: 222},
{Id: 333},
{Id: 111},
]
}
const sentPayload = {
Lines: [
{LineId: 111},
{LineId: 222},
{LineId: 333},
{LineId: 111},
]
}
function updateDbSent() {
const param = [];
sentPayload.Lines.forEach((line) => {
let lineId = line.LineId
for (const dbItemIndex in dbData.Items) {
if (dbData.Items[dbItemIndex].Id == lineId) {
param.push({
Index: dbItemIndex,
Sent: true,
Id: lineId,
})
}
}
});
//update db
console.log(param);
}
updateDbSent()
我希望是:
[
{
"Index": "0",
"Sent": true,
"Id": 111
},
{
"Index": "1",
"Sent": true,
"Id": 222
},
{
"Index": "2",
"Sent": true,
"Id": 333
},
{
"Index": "3",
"Sent": true,
"Id": 111
}
]
答案 0 :(得分:1)
您可以从客户端sendPayload中删除重复项,以获取正确的输出。
当前,在数据库中两次检查了相同的有效负载ID(在这种情况下为1111) 要删除重复项,可以使用Set。
const lineIds = new Set();
sentPayload.Lines.forEach(lineIdObj => lineIds.add(lineIdObj.LineId))
现在,就像您在当前代码中一样,只需循环lineIds
即可。
function updateDbSent() {
const param = [];
lineIds.forEach((lineId) => {
for (const dbItemIndex in dbData.Items) {
if (dbData.Items[dbItemIndex].Id == lineId) {
param.push({
Index: dbItemIndex,
Sent: true,
Id: lineId,
})
}
}
});
//update db
console.log(param);
}
答案 1 :(得分:1)
您的解决方案看起来有点复杂。我会建议一种利用减少和查找索引的解决方案,如下所示:
const dbData = {
Items: [{ Id: 111 }, { Id: 222 }, { Id: 333 }, { Id: 111 }],
};
const sentPayload = {
Lines: [{ LineId: 111 }, { LineId: 222 }, { LineId: 333 }, { LineId: 111 }],
};
更新实现。我更新了解决方案,改为使用reduce并将索引和id组合用作键
function updateDbSent() {
const result = sentPayload.Lines.reduce((acc, line, lineIndex) => {
const { LineId } = line;
const Index = dbData.Items.findIndex(
(item, itemIndex) => item.Id === LineId && !acc[`${line} - ${itemIndex}`]
);
acc[`${line} - ${Index}`] = {
Index,
Id: LineId,
Sent: true,
};
return acc;
}, {});
return Object.values(result);
//update db
}
console.log(updateDbSent());
答案 2 :(得分:0)
在foreach中使用闯入for循环和累加器并推入累加器
const dbData = {
Items: [
{ Id: 111 },
{ Id: 222 },
{ Id: 333 },
{ Id: 111 },
]
}
const sentPayload = {
Lines: [
{ LineId: 111 },
{ LineId: 222 },
{ LineId: 333 },
{ LineId: 111 },
]
}
function updateDbSent() {
const param = [];
sentPayload.Lines.forEach((line, accumulator ) => {
let lineId = line.LineId;
for (const dbItemIndex in dbData.Items) {
if (dbData.Items[dbItemIndex].Id == lineId) {
param.push({
Index: accumulator ,
Sent: true,
Id: lineId,
});
break;
}
}
});
//update db
console.log(param);
}
updateDbSent()