比较两个列表,如果不同则更新
Comparing Two Lists, Updating if Different
我有一个用 JavaScript 编写的程序,它根据一个列表中的项目是否与另一个不同来运行 CRUD 操作。基本上比较两个列表,主列表和镜像列表。约束是:
如果一个对象在主列表中,但不在镜像列表中,则将其添加到镜像列表中
如果一个对象在镜像列表中,但不在主列表中,则将其从镜像列表中删除
执行此检查的有效方法是什么?目前,我正在迭代两个似乎效率低下的 for 循环。
for (const mainId of Object.keys(mainItems)) {
if (!Object.keys(mirrorItems).includes(mainId)) {
await createEvent(mainItems[mainId])
}
}
for (const mirrorId of Object.keys(mirrorItems)) {
if (!Object.keys(mainItems).includes(mirrorId)) {
await deleteEvent(mirrorItems[mirrorId])
}
}
从您的代码看来,您正在比较对象的键,而不仅仅是任意数组。因此,您可能希望 mirrorItems
具有与 mainItems
相同的键,但具有不同的值(否则它只是一个副本)。
使用在 O(1)
中执行查找的 Set
将您的解决方案从 O(n²)
中的解决方案 运行 提升为 [=17= 中的 运行 ].
另外你需要reduce()
.
const obj = {
matching: "A matching property but a diferrent value",
missing: "A property which is missing in mirror, should be added",
};
const mirror = {
matching:
"A matching property but a diferrent value, to see that there is not just a copy created",
additional: "An additional property which should be deleted",
};
const set = new Set(Object.keys(mirror));
const correctMirror = Object.keys(obj).reduce(
(mirrored, cur) => (
set.has(cur)
? // if the property exist on the obj, we can keep the current value
(mirrored[cur] = mirror[cur])
: // if the property does not exist on obj, we need to get the value from obj and assign it to the mirror
(mirrored[cur] = obj[cur]),
// return mirrored for next iteration or result
mirrored
),
{}
);
console.log(correctMirror);
.as-console-wrapper { max-height: 100% !important; top: 0; }
我有一个用 JavaScript 编写的程序,它根据一个列表中的项目是否与另一个不同来运行 CRUD 操作。基本上比较两个列表,主列表和镜像列表。约束是:
如果一个对象在主列表中,但不在镜像列表中,则将其添加到镜像列表中
如果一个对象在镜像列表中,但不在主列表中,则将其从镜像列表中删除
执行此检查的有效方法是什么?目前,我正在迭代两个似乎效率低下的 for 循环。
for (const mainId of Object.keys(mainItems)) {
if (!Object.keys(mirrorItems).includes(mainId)) {
await createEvent(mainItems[mainId])
}
}
for (const mirrorId of Object.keys(mirrorItems)) {
if (!Object.keys(mainItems).includes(mirrorId)) {
await deleteEvent(mirrorItems[mirrorId])
}
}
从您的代码看来,您正在比较对象的键,而不仅仅是任意数组。因此,您可能希望 mirrorItems
具有与 mainItems
相同的键,但具有不同的值(否则它只是一个副本)。
使用在 O(1)
中执行查找的 Set
将您的解决方案从 O(n²)
中的解决方案 运行 提升为 [=17= 中的 运行 ].
另外你需要reduce()
.
const obj = {
matching: "A matching property but a diferrent value",
missing: "A property which is missing in mirror, should be added",
};
const mirror = {
matching:
"A matching property but a diferrent value, to see that there is not just a copy created",
additional: "An additional property which should be deleted",
};
const set = new Set(Object.keys(mirror));
const correctMirror = Object.keys(obj).reduce(
(mirrored, cur) => (
set.has(cur)
? // if the property exist on the obj, we can keep the current value
(mirrored[cur] = mirror[cur])
: // if the property does not exist on obj, we need to get the value from obj and assign it to the mirror
(mirrored[cur] = obj[cur]),
// return mirrored for next iteration or result
mirrored
),
{}
);
console.log(correctMirror);
.as-console-wrapper { max-height: 100% !important; top: 0; }