1

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
asked Jun 5, 2013 at 19:15
2
  • 1
    what 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? Commented Jun 5, 2013 at 19:18
  • If I am not wrong you want to merge object in reference to same "name"? Commented Jun 5, 2013 at 19:20

1 Answer 1

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
1
  • 1
    great, 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. Commented Jun 6, 2013 at 4:57

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.