首页 > 解决方案 > 跟踪删除的对象,在比较字符串中的两个对象数组后添加

问题描述

假设我有两个 Object 数组,

let oldBookDetails = [
    {'name':'Harry pottar','amount':10, is_modified: false},
    {'name':'LOTR','amount':20, is_modified: false},
    {'name':'dune','amount':15, is_modified: false}
]

let newBookDetails = [
    {'name':'Harry pottar','amount':15},
    {'name':'LOTR','amount':20},
    {'name':'HR','amount':15}
]

在堆栈溢出成员@Tushar Shahi 的帮助下,在下面的解决方案的帮助下,我通过比较 oldBookDetails 和 newBookDetails 来获取已修改为新数组的对象,我尝试了,

let componentRemovedNote = "The centre has added ";
let componentAddedNote = "The center has removed ";

let bookModified = newBookDetails.map((x) => {
    let foundBook = oldBookDetails.find((old) => old.name === x.name);
    if (foundBook) {
        if (foundBook.amount !== x.amount) {
            if (foundBook.amount < x.amount) {
                componentAddedNote += `${foundBook.name} - ${foundBook.amount}`;
                return { ...x, is_modified: true };
            } else {
                componentRemovedNote += ` ${x.name} - ${x.amount} `;
                return { ...x, is_modified: true };
            }
        } else return { ...x, is_modified: false };
    } else {
        componentAddedNote += `${x.name} - ${x.amount}`;
        return { ...x, is_modified: true };
    }
});

bookDetails 数组的预期结果是正确的,但我也想将注释记为:

所有者添加 Harry Pottar - 10(原始值),HR - 15(新值)

所有者移除沙丘 - 15

我尝试的解决方案是在 componentRemovedNote 和 componentAddedNote 中给我带来的价值。

如果有人需要任何进一步的信息,请告诉我。

标签: javascriptnode.jsarraysobject

解决方案


推荐阅读