I have two nested json files loaded into my NodeJS app, the second one is just newer version of first one - with more keys.

First one is something like this

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

second one has more keys than first one, and some values are different

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

I want to be able to merge those two json objects, not only update keys that are presented in first one but also add all keys that are not existing in it and are present in second one. How could i achieve this, most simple and easy to understand way?

I have tried this code

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

And it does it job with merging two files together but its always doing it only for keys that are present in this object and i have no idea how could i modify it to make it add even non existing keys.

This is what i want to get at the end, after combining those two json objects from above:

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

1 Answers

2
Jack Bashford On

Since you want to update the first object with keys from the second, use spreading:

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