javascript - 合并两个相似的 JSON 对象,但一个在 NodeJS 中有更多键
问题描述
我有两个嵌套的 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);
推荐阅读
- android - 如何在 Android Studio/Intellij 中显示代码重新格式化快捷方式的警告
- scrapy - 刮掉 div 标签下的引号中的文本
- c++ - 访问网格数据时 assimp segfault
- python - 使用 0 值的 Counter 填充列表
- sql - SSMS:自动将来自同一 SQL 脚本的多个结果集保存到 Excel 中的单独选项卡中?
- python - 如何在 Python 中编辑 Facebook 帖子?
- amazon-web-services - AWS StepFunctions - 合并和展平与原始输入相结合的任务输出
- tree - 如何在prolog中计算一棵树的叶子?
- .net - 在边缘下载文件的页面名称不是 .net 中的文件名
- flutter - 双飞镖/颤振自动铸造的影响