I have a JSON array with nested objects, as below:
var cData = [{
"name": "Jack Doe",
"desc": "Jack",
"values": [{
"id": "615",
"subject": "Physics",
"Grade": "B"
}, {
"id": "616",
"subject": "Chemistry",
"Grade": "A"
}]
},
{
"name": "Jane Doe",
"desc": "Jane",
"values": [{
"id": "715",
"subject": "Maths",
"Grade": "A+"
}]
},
{
"name": "Jack Doe",
"desc": "Jack",
"values": [{
"id": "617",
"subject": "Maths",
"Grade": "A"
}]
},
{
"name": "Jane Doe",
"desc": "Jane",
"values": [{
"id": "716",
"subject": "Physics",
"Grade": "B"
}]
}]
I want to consolidate objects in above array to
var cData = [{
"name": "Jack Doe",
"desc": "Jack",
"values": [{
"id": "615",
"subject": "Physics",
"Grade": "B"
}, {
"id": "616",
"subject": "Chemistry",
"Grade": "A"
}, {
"id": "617",
"subject": "Maths",
"Grade": "A"
}]
},
{
"name": "Jane Doe",
"desc": "Jane",
"values": [{
"id": "715",
"subject": "Maths",
"Grade": "A+"
}, {
"id": "716",
"subject": "Physics",
"Grade": "B"
}]
}]
If any one has any suggestions for me it'd be really great! jQuery methods are also welcome.
Ram
145k16 gold badges174 silver badges201 bronze badges
-
1what have you tried so far? also are you looking to merge the records based on the name field or the description field? how should differences in the other field be handled?Ben McCormick– Ben McCormick2013年06月05日 19:18:15 +00:00Commented Jun 5, 2013 at 19:18
-
If I am not wrong you want to merge object in reference to same "name"?pvnarula– pvnarula2013年06月05日 19:20:00 +00:00Commented Jun 5, 2013 at 19:20
1 Answer 1
You have to write function to merge array of objects under key and then get map values. Here it is:
Merge function:
function mergeArray(array) {
var merged = {};
$.each(array, function() {
var item = this;
// Use name as a key
if (typeof merged[item.name] != 'undefined') {
// merge values array
$.merge(merged[item.name].values, item.values);
}
else {
merged[item.name] = item;
}
});
// get values from { key1: value1, key2: value2, ... } object
return getObjectValues(merged);
}
Getting values from object:
function getObjectValues(obj) {
var values = [];
$.each(obj, function(key,valueObj){
values.push(valueObj);
});
return values;
}
Here is working example.
answered Jun 5, 2013 at 19:49
-
1great, working perfectly fine when I did included this in my program . I was working on this last two days could not able to figureout. Thank you very much for quick solution.AnuNag– AnuNag2013年06月06日 04:57:43 +00:00Commented Jun 6, 2013 at 4:57
Explore related questions
See similar questions with these tags.
lang-js