在JSON数组中组合嵌套对象
问题描述:
我有一个带有嵌套对象的JSON数组,如下所示:
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"
}]
}]
如果有人对我有任何建议,那就太好了!也欢迎使用jQuery方法.
If any one has any suggestions for me it'd be really great! jQuery methods are also welcome.
答
您必须编写函数以合并键下的对象数组,然后获取映射值. 在这里:
You have to write function to merge array of objects under key and then get map values. Here it is:
合并功能:
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;
}
这是工作示例.