gpt4 book ai didi

javascript - 提取两个对象(甚至嵌套对象)之间不同的键值有什么方法?

转载 作者:行者123 更新时间:2023-11-30 13:49:18 24 4
gpt4 key购买 nike

我想比较两个几乎总是具有相同属性的对象,并根据具有与第一个对象不同的值的属性创建一个新对象。在下面的示例中,我想检查 inputData 是否有任何与 currentData 不同的键:值。然后根据这些键和值创建一个新对象。希望它有意义?我应该采用什么方法?一些递归的 Oject.assign?传播操作?循环?

const currentData = {
title: 'John',
email: 'info@abc.com'
address {
street: 'myStreet 13'
}
}

const inputData = {
title: 'Tom',
email: 'info@abc.com',
address {
street: 'yourStreet 17'
}
}

结果应该是这样的:

const result = {
title: 'Tom',
address: {
street: 'yourStreet 17'
}
}

最佳答案

您需要一个循环遍历对象的递归函数,大致如下:

function compareObjects(a, b) {
// Assume they'll be the same
let result = null;
// Keep track of the keys we've seen
let keys = new Set();
for (const key in a) {
keys.add(key);
if (!(key in b)) {
// You'll want to decide what to do here, use `undefined`?
} else {
const avalue = a[key];
const bvalue = b[key];
if (avalue !== bvalue) {
const aIsObject = typeof avalue === "object";
const bIsObject = typeof bvalue === "object";
if (aIsObject && bIsObject) {
// Both are objects, recurse
const update = compareObjects(avalue, bvalue);
if (update) {
result = result || {};
result[key] = update;
}
} else {
// Different values
result = result || {};
result[key] = bvalue;
}
}
}
}
// Add in any that are in `b` but weren't in `a`
for (const key in b) {
if (!keys.has(key)) {
result = result || {};
result[key] = b[key];
}
}
return result;
}

实例:

const currentData = {
title: 'John',
email: 'info@abc.com',
address: {
street: 'myStreet 13'
}
};

const inputData = {
title: 'Tom',
email: 'info@abc.com',
address: {
street: 'yourStreet 17'
}
};

function compareObjects(a, b) {
// Assume they'll be the same
let result = null;
// Keep track of the keys we've seen
let keys = new Set();
for (const key in a) {
keys.add(key);
if (!(key in b)) {
// You'll want to decide what to do here, use `undefined`?
} else {
const avalue = a[key];
const bvalue = b[key];
if (avalue !== bvalue) {
const aIsObject = typeof avalue === "object";
const bIsObject = typeof bvalue === "object";
if (aIsObject && bIsObject) {
// Both are objects, recurse
const update = compareObjects(avalue, bvalue);
if (update) {
result = result || {};
result[key] = update;
}
} else {
// Different values
result = result || {};
result[key] = bvalue;
}
}
}
}
// Add in any that are in `b` but weren't in `a`
for (const key in b) {
if (!keys.has(key)) {
result = result || {};
result[key] = b[key];
}
}
return result;
}

console.log(compareObjects(currentData, inputData));

关于javascript - 提取两个对象(甚至嵌套对象)之间不同的键值有什么方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58590610/

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