gpt4 book ai didi

javascript - 比较 2 个对象并删除它们之间的重复键

转载 作者:行者123 更新时间:2023-11-29 23:51:13 25 4
gpt4 key购买 nike

我正在对对象进行试验,我想要实现的是删除 object1 中找到的键(如果这些键存在于 object2 中)。

例子如下:

var original = {
a: 1,
b: 2,
c: 3,
e: {
tester: 0,
combination: {
0: 1
}
},
0: {
test: "0",
2: "hello"
}
};

var badKeys = {
a: 1,
b: 2,
0: {
test: "0",
}
}


var expectedResult = {
c: 3,
e: {
tester: 0,
combination: {
0: 1
}
},
0: {
2: "hello"
}

}

我尝试过使用underscore 差异函数,但它对对象不起作用,也不确定这是否是正确的函数。

你能帮我得到正确的 var expectedResult 吗?

最佳答案

您可以使用迭代和递归方法在新对象中获取所需的属性。

function deleteKeys(good, bad, result) {
Object.keys(good).forEach(function (key) {
if (bad[key] && typeof bad[key] === 'object') {
result[key] = {};
deleteKeys(good[key], bad[key], result[key]);
return;
}
if (!(key in bad) || good[key] !== bad[key]) {
result[key] = good[key];
}
});
}

var original = { a: 1, b: 2, c: 3, e: { tester: 0, combination: { 0: 1 } }, 0: { test: "0", 2: "hello", another: { a: { B: 2, C: { a: 3 } }, b: 2 } } },
badKeys = { a: 1, b: 2, 0: { test: "0", random: 2, another: { a: 1 } } },
result = {};

deleteKeys(original, badKeys, result);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 比较 2 个对象并删除它们之间的重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42734895/

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