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

时间:2019-04-21 20:24:13

标签: 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"
  }
}

1 个答案:

答案 0 :(得分:2)

由于要使用第二个对象的键更新第一个对象,请使用散布:

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);

相关问题