gpt4 book ai didi

javascript - 合并两个相似的 JSON 对象,但一个在 NodeJS 中具有更多键

转载 作者:行者123 更新时间:2023-12-01 01:04:12 27 4
gpt4 key购买 nike

我有两个嵌套的 json 文件加载到我的 NodeJS 应用程序中,第二个只是第一个文件的更新版本 - 具有更多键。

第一个是这样的

{
"something": {
"first": "one",
"second": "two"
},
"somethingelse": {
"one": "first string",
"two": "second string"
}
}

第二个比第一个有更多的键,并且某些值不同

{
"something": {
"first": "one",
"second": "two",
"third": "this one changed "
},
"somethingelse": {
"one": "first string and this one changed",
"two": "second string",
"three": "third string"
}
}

我希望能够合并这两个 json 对象,不仅更新第一个对象中出现的键,还添加其中不存在但第二个对象中出现的所有键。我怎样才能实现这个最简单易懂的方式?

我已经尝试过这段代码

function matchjson(json1, json2) {
var combined_json = {};
var i = 0
// Deep copy of json1 object literal
for (var key in json1) {

combined_json[key] = json1[key];

}
for (var key in json2) {
// console.log(key)
if (!json1.hasOwnProperty(key)) combined_json[key] = json2[key]
}
return combined_json;
}

它的工作是将两个文件合并在一起,但它总是只针对该对象中存在的键执行此操作,我不知道如何修改它以使其添加甚至不存在的键。

这就是我在组合上面的两个 json 对象后最终想要得到的:

{
"something": {
"first": "one",
"second": "two",
"third": "this one changed "
},
"somethingelse": {
"one": "first string and this one changed",
"two": "second string",
"three": "third string"
}
}

最佳答案

由于您想使用第二个对象的键更新第一个对象,因此请使用传播:

const json1 = {"something": {"first": "one","second": "two",},"somethingelse": {"one": "first string","two": "second string",}};
const json2 = {"something": {"first": "one","second": "two","third": "this one changed "},"somethingelse": {"one": "first string and this one changed","two": "second string","three": "third string"}};
const json3 = { ...json1, ...json2 };
console.log(json3);

关于javascript - 合并两个相似的 JSON 对象,但一个在 NodeJS 中具有更多键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55786459/

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