0

My aim is to combine 2 similar JSON objects so that the output will have its value taken from the json objects supplied. For eg:

var obj1 = {'name': 'xyz', 'age':''}, obj2 = {'name':'', 'age':'66'}
//would like to have some functionality like below that gives me the output
obj3 = combine(obj1,obj2) 
//desired output below.
obj3 = {'name': 'xyz', 'age':'66'}
Kapil gopinath
  • 1,053
  • 1
  • 8
  • 18

3 Answers3

1

Since you say the two objects are similar I am going to assume that this means for those keys which are common among the two objects one has data and other has ''.

The second assumption I am going to make is that for any keys not common to both the objects you want it to be copied as is to the new object.

var obj1 = {'a': 'b', 'c': ''};
var obj2 = {'a': '', 'c': 'd', 'e': 'f'};
var obj3 = {};
var key;

for (key in obj1) {
    if(obj1[key] === '') {
        obj3[key] = obj2[key];
    } else {
        obj3[key] = obj1[key];
    }
}

for(key in obj2) {
    if(!(key in obj3)) {
        obj3[key] = obj2[key];
    }
}
Prathik Rajendran M
  • 1,152
  • 8
  • 21
0

Since you added the jQuery tag, I assume you are using it. If so, you can use jQuery's $.extend method.

var obj1 = {'name': 'xyz', 'age':''},
    obj2 = {'name':'', 'age':'66'},
    obj3 = $.extend(obj1,obj2);
rabelloo
  • 376
  • 2
  • 5
  • 1
    I tried $.extend , but that won't give the desired output – Kapil gopinath Dec 26 '16 at 12:48
  • You are correct. For it to work, you can't have empty properties. Try deleting all of them beforehand like suggested here: http://stackoverflow.com/questions/23774231/how-do-i-remove-all-null-and-empty-string-values-from-a-json-object – rabelloo Dec 26 '16 at 12:57
0

I'm not entirely sure about what the disired result is, but this code should point you in the right direction. It copies values from obj2 to obj1, if the value has a value (with isnt empty or false):

combine = function(a, b) {
 var bKeys = Object.keys(b)
 for (var i = 0; i < bKeys.length; i++) {
   var key = bKeys[i]
   if (b[key]) {
     a[key] = b[key]
   }
 }
}
Martin
  • 2,302
  • 2
  • 30
  • 42