Combining Nested Objects in a JSON Array

久未见 提交于 2020-01-15 09:13:07

问题


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.


回答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.



来源:https://stackoverflow.com/questions/16948009/combining-nested-objects-in-a-json-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!