为什么param
在最多4个对象时生成了太多的对象。它应该匹配dbData.Items[dbItemIndex].Id == lineId
和param
中的商店元数据之间的Id,包括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
}
]
您的解决方案看起来有点复杂。我会建议一个利用reduce和find index的解决方案如下
const dbData = {
Items: [{ Id: 111 }, { Id: 222 }, { Id: 333 }, { Id: 111 }],
};
const sentPayload = {
Lines: [{ LineId: 111 }, { LineId: 222 }, { LineId: 333 }, { LineId: 111 }],
};
在作者指出我的解决方案不能与重复的Id一起使用之后更新实现。我更新了解决方案以使用reduce和make index和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());
您可以从客户端sentPayload中删除重复项以获得正确的输出。
目前,在DB中检查两次相同的有效负载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);
}
在foreach中使用break in 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()