首页 > 解决方案 > 合并两个相似的 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"
  }
}

标签: javascriptnode.jsjsonobject

解决方案


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

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


推荐阅读