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
Asked
Active
Viewed 63 times
-1

Eshank Jain
- 169
- 3
- 14
-
What's the question? Also why would one care about sequences of keys? – PeeHaa Jun 23 '16 at 18:50
-
In Javascript, objects have no order. For merging, see [this question](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically). – Blackhole Jun 23 '16 at 18:54
-
Hashes keys order is implementation defined, so nothing you can do about their order actually :( – axelduch Jun 23 '16 at 18:54
-
I am using Object.assign(merged, obj1, obj2) but it doesn't work – Eshank Jain Jun 23 '16 at 18:55
-
Loop on the array before merging. – Blackhole Jun 23 '16 at 19:01
-
Got the result by looping over the array :) – Eshank Jain Jun 24 '16 at 18:38
-
But I am getting an array of arrays.... I am looking for an array of objects – Eshank Jain Jun 24 '16 at 18:41
-
Got the array of objects as well ... now just need to sort them on the basis of some particular columns – Eshank Jain Jun 24 '16 at 19:14
2 Answers
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;
});
}