-1
  • First JSON in input

    var obj1 = [{
                    "name":"manu",
                    "age":23,
                    "occupation":"SE"
                },
                {   
                    "name":"test",
                    "age":22,
                    "occupation":"TE"
                }
               ];
    
    • Second JSON in input

       var obj2 = [{
                  "age":23,
                  "name":"manu",
                  "gender":"male"
              },
              {   
                  "age":22,
                  "name":"test",
                  "gender":"male"
              }
             ];
      
    • Resulting JSON required after merging

      var result = [{
                  "name":"manu",
                  "age":23,
                  "occupation":"SE",
                  "gender":"male"
              },
              {   
                  "name":"test",
                  "age":22,
                  "occupation":"TE",
                  "gender":"male"
              }
             ];
      
    • please see the arrangement in which keys are arranged in JSON

    • They are not in same order (age and name ) keys in object
Eshank Jain
  • 169
  • 3
  • 14

2 Answers2

1

You could use a special callback for merging the arrays to a new one result with the matching key and all other properties.

function mergeTo(target, key) {
    var ref = Object.create(null);
    return function (o) {
        if (!ref[o[key]]) {
            ref[o[key]] = {};
            target.push(ref[o[key]]);
        }
        Object.keys(o).forEach(function (k) {
            ref[o[key]][k] = o[k];
        });
    };
}

var obj1 = [{ "name": "manu", "age": 23, "occupation": "SE" }, { "name": "test", "age": 22, "occupation": "TE" }],
    obj2 = [{ "age": 23, "name": "manu", "gender": "male" }, { "age": 22, "name": "test", "gender": "male" }],
    result = [],
    merge = mergeTo(result, 'name');

obj1.forEach(merge);
obj2.forEach(merge);
    
console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You have two arrays where each index in the array is an object. If the array indexes go together, as in your example, then just loop and assign.

var length = obj1.length;
for( var idx = 0; idx < length; idx++ )
{
  var tmpObj = obj2[ idx ];
  Object.keys(tmpObj).forEach(function(key,index)
  {
     // key: the name of the object key
     // index: the ordinal position of the key within the object 

     // create new object property based upon the variable key
     // and assign it the corresponding value from obj2
     obj1[ idx ][ key ] = tmpObj.key;
  });
}

Iterate over Object

Using variables as key names

Community
  • 1
  • 1
Aaron
  • 428
  • 5
  • 14