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

标签 javascript node.js json object

我有两个嵌套的 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/

相关文章:

javascript - 使用 jquery 停用浏览器滚动条

javascript - Angular : How to spy on $element. 开启

javascript - 你能安全地将 JavaScript 类实例存储在 Redis 中吗?

java - Jackson JSON 映射键作为包含对象的属性

javascript - 从 json feed 中删除时间

javascript - 在 POST 上将 javascript 对象读取为 JSON

javascript - 如何从 JSON 对象中获取值?

javascript - 使用随机键处理 Javascript 对象

node.js - AWS SSM 错误 : UnexpectedParameter: Unexpected key 'CloudWatchOutputConfig'

javascript - 关闭 CS :GO Dedicated Server via Node. js child_process