1

我有一个带有嵌套对象的 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 方法。

4

1 回答 1

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

这是工作示例

于 2013-06-05T19:49:04.830 回答