在JSON数组中组合嵌套对象

时间:2013-06-05 19:15:26

标签: javascript jquery arrays json object

我有一个带有嵌套对象的JSON数组,如下所示:

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"
    }]
}]

我想将上面数组中的对象合并到

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"
    }]
}]

如果有人对我有任何建议,那真的很棒! jQuery方法也很受欢迎。

1 个答案:

答案 0 :(得分:1)

您必须编写函数来合并键下的对象数组,然后获取地图值。 这是:

合并功能:

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);
}

从对象获取值:

function getObjectValues(obj) {
    var values = [];
    $.each(obj, function(key,valueObj){
        values.push(valueObj);
    });
    return values;
}

这是working example