合并2个数组,更新值

时间:2019-07-19 09:16:24

标签: javascript

在我的化简器中,我要从API中提取结果,我想将此数组与存储中的持久数据(如果存在)结合起来,数据中唯一需要覆盖的字段是bookMarkedtotalScorecompleted。我如何比较数组并覆盖所需的属性(如果它们不同)?

最好的方法是什么?

let arrayFromAPI= [
    {
        bookMarked: false,
        completed: false,
        totalScore: 50,
        current: 0,
        description:
            "<p>Lorem ipsum culpa qui officia deserunt mollit anim id est laborum.</p>",
        icon: "male-urinary-catheterisation",
        id: 1
    },
    {
        bookMarked: false,
        completed: false,
        totalScore: 50,
        current: 0,
        description:
            "<p>Lorem ipsum culpa qui officia deserunt mollit anim id est laborum.</p>",
        icon: "male-urinary-catheterisation",
        id: 2
    }
];

let arrayFromPersist = [
    {
        bookMarked: true,
        completed: false,
        totalScore: 50,
        completed: true,
        current: 0,
        description:
            "<p>Lorem ipsum culpa qui officia deserunt mollit anim id est laborum.</p>",
        icon: "male-urinary-catheterisation",
        id: 1
    },
    {
        bookMarked: true,
        completed: false,
        totalScore: 50,
        completed: true,
        current: 0,
        description:
            "<p>Lorem ipsum culpa qui officia deserunt mollit anim id est laborum.</p>",
        icon: "male-urinary-catheterisation",
        id: 2
    }
];

1 个答案:

答案 0 :(得分:0)

您可以使用过滤器并根据属性ID将arrayFromAPI响应中的所有值合并到arrayFromPersist,因为两个数组中的值必须相同才能替换{{ 1}}

arrayFromAPI