0

Given a json like this

  var json1 = {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": null
      };

  var json2 = {
                "key3": {
                  "index": "3",
                  "value": "value3"
                },
                "key4": {
                  "index": "4",
                  "value": 'value4'
              }
        };

how to get a new json like this, it will only copy the same key to the first one.

json3= {
        "key1": {
          "index": "1",
          "value": null
        },
        "key2": {
          "index": "2",
          "value": null
        },
        "key3": {
          "index": "3",
          "value": 'value3'
      }
};

I've tried on Object.assign or _.assign of lodash

 Object.assign(json1,json2)
 _.assign(json1,json2)

but it will copy all the objects of json2 to json1.

Jerry
  • 329
  • 1
  • 4
  • 13

3 Answers3

3

You can use Object.keys to get all the keys from json1 then check if the key exist in json2,if it exists then get the value corresponding to that key from json2

var json1 = {
  "key1": {
    "index": "1",
    "value": null
  },
  "key2": {
    "index": "2",
    "value": null
  },
  "key3": {
    "index": "3",
    "value": null
  }
}

var json2 = {
  "key3": {
    "index": "3",
    "value": "value3"
  },
  "key4": {
    "index": "4",
    "value": 'value4'
  }
};

Object.keys(json1).forEach((item) => {
  if (json2.hasOwnProperty(item)) {
    json1[item].value = json2[item].value
  }
})
console.log(json1)
brk
  • 48,835
  • 10
  • 56
  • 78
  • Thanks! If each key's depth in json1 and json2 be uncertain, is it possible to get a recursive function to do this ? – Jerry Feb 20 '20 at 14:23
1

const json1 = {
    "key1": {
      "index": "1",
      "value": null
    },
    "key2": {
      "index": "2",
      "value": null
    },
    "key3": {
      "index": "3",
      "value": null
  }
};

const json2 = {
        "key3": {
          "index": "3",
          "value": "value3"
        },
        "key4": {
          "index": "4",
          "value": 'value4'
      }
};

const result = {};
for(const key in json1) {
  result[key] = json2[key] ? json2[key] : json1[key];
};

console.log(result);
You can use a for in for it.
Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
0

Live Demo: https://runkit.com/embed/0z916nnwl2w5

var output = Object.assign(json1,json2);
delete output.key4;  //Here is the key~~~
console.log(output);

enter image description here

David
  • 15,894
  • 22
  • 55
  • 66
  • boo. this does what he wants, but its not realistic because it will required a code change if json2 has key5. basically he wants the diff(1 & 2) + instersection(1 &2): https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript/11353526 – LostJon Feb 20 '20 at 20:59