gpt4 book ai didi

javascript - 查找数组对象的值差异

转载 作者:行者123 更新时间:2023-12-01 02:47:30 25 4
gpt4 key购买 nike

我有两个数组,它们都由随机键和值组成。我有一个更新的对象和当前对象。但更新后的对象包含新值和旧值。我想找到这两个对象键和值之间的差异,以使用新键或值生成新的更新对象。

当前对象

{
key1: "abc"
key2: "ggg"
key3: 0,
key4: ["1","3","5"]
key5: [1,2,3,4,5]
key6: [9,8,7,6],
key7: false
}

更新对象

{
key1: "abc"
key2: "new"
key3: 30,
key4: ["1","3","5"]
key5: [2,3,4]
key6: [],
key7: true,
special8: [1,2,3]
}

结果

{
key2: "new"
key3: 30,
key5: [2,3,4]
key6: [],
key7: true,
special8: [1,2,3]
}

最佳答案

根据您的条件:以下 reduce() 函数将每个更新的对象的属性与每个当前对象的属性进行比较并返回一个包含差异的全新对象。

请注意:使用 !== 简单地浅比较字符串数组(例如您的 key4 属性)可能会返回漏报,因此使用 JSON .stringify().

// Current Object.
const current = {
key1: "abc",
key2: "ggg",
key3: 0,
key4: ["1","3","5"],
key5: [1,2,3,4,5],
key6: [9,8,7,6],
key7: false
}

// Updated Object.
const updated = {
key1: "abc",
key2: "new",
key3: 30,
key4: ["1","3","5"],
key5: [2,3,4],
key6: [],
key7: true,
special8: [1,2,3]
}

// Difference Object.
const difference = (Object.keys(updated)).reduce((difference, key) => {

// Same?
if (JSON.stringify(updated[key]) == JSON.stringify(current[key])) return difference

// Different.
return {...difference, [key]: updated[key]}

}, {})

console.log(difference)

关于javascript - 查找数组对象的值差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47171159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com