How to copy keys and values ​​from one object to another without copying the values

advertisements

I have 2 objects

json1 = {
    "name": "padd",
    "value": "1",
    "parentName": "",
    "parentValue": "",
    "children": [],
    "canDisplay": true,
    "showRecord": true
}

json2 = {
    "name": "note",
    "value": "1",
    "parentName": "",
    "parentValue": "",
    "children": [{
        "name": "padd",
        "value": "1",
        "parentName": "",
        "parentValue": "",
        "children": [],
        "canDisplay": true,
        "showRecord": true
    }],
    "canDisplay": true,
    "showRecord": true
}

The keys which are missing in json1 should be added from json2 and also the values of the keys which are matching in json1 and json2 should not be replaced from json2 to json1.


You could use the Object.keys method, to loop through keys of json1, and if key is not found in json2, set it to a blank string. e.g.

var keys1 = Object.keys(json1);
for (var key_i=0; key_i<keys1.length; key_i++) {
  var key = keys1[key_i];
  if (typeof json2[key] === 'undefined') {
    json2[key] = '';
  }
}

Edit:

If you want to copy over values from json1 to json2, if not in json2, then change:

json2[key] = '';

to

json2[key] = json1[key];