Reputation: 21
I have five json objects obj1 ,obj2,obj3,obj4 and obj5, i want to merge them and crete a single json object and obj have same columns. The resultant json should have all the values from all objects
Question:
var obj1 = {
"DOP":"manu",
"Resolution":23,
"sensor":"SE"
}
var obj2 = {
"DOP":"mansa",
"Resolution":22,
"sensor":"PS"
}
like that all five object data and results should update only rows not as columns and expected result should be
var result = {
"Dop":["manu","mansa"],
"Resolution":[23,25],
"Sensor":["SE","PS"]
}
Upvotes: 2
Views: 2521
Reputation: 8496
You can merge object based on passing unlimited objects as arguments in myCustomMerge()
function
function myCustomMerge() {
var return_obj = {};
for (i in arguments) {
obj = arguments[i];
for (j in obj) {
if (return_obj[j] == undefined) {
return_obj[j] = [obj[j]];
} else {
return_obj[j].push(obj[j]);
}
}
}
return return_obj;
}
var obj1 = {
"DOP": "manu",
"Resolution": 23,
"sensor": "SE"
}
var obj2 = {
"DOP": "mansa",
"Resolution": 22,
"sensor": "PS",
"special_obj2": "My Special Value"
}
var obj3 = {
"DOP": "top",
"Resolution": 36,
"sensor": "ME",
"special_obj2": "My Special Value 2"
}
var merged_obj = myCustomMerge(obj1, obj2, obj3);
console.log(merged_obj);
Upvotes: 1
Reputation: 41
var x ={ "student-marks":{'math':1,'physics':5} };
var y ={ "student-marks":{'chemistry':3,'history':2} };
$.extend(true, {}, x, y);
I got the answer from here: How to merge two object values by keys
Upvotes: 0
Reputation: 1674
The way you want result is illegal. All you can have array of your json.
var result = [{ "DOP":"mansa", "Resolution":22, "sensor":"PS" },
{ "DOP":"manu", "Resolution":23, "sensor":"SE" }
]
Upvotes: 0
Reputation: 4615
You can use for(x in obj)
var result = {}
for (x in obj1) { result[x] = obj1[x] + ', ' + obj2[x] }
//Object {DOP: "manu, mansa", Resolution: "23, 22", sensor: "SE, PS"}
Upvotes: 1