我有一个像这样的
JSON对象数组
var dataSet1 = [{
"id": "1",
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
"version": "5",
"grade": "X"
}, {
"id": "2",
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
"version": "5",
"grade": "A"
}, {
"id": "3",
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
"version": "4",
"grade": "X"
},
{
"id": "4",
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
"version": "5",
"grade": "A"
}];
我想循环遍历此数据集并创建一个新的对象数组,这些对象将具有相似“等级”属性的对象合并,并保留其关联的“id”和“version”值的列表,如此
“等级”属性等于“X”的旧对象
{
"id": "1",
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
"version": "5",
"grade": "X"
}
{
"id": "3",
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
"version": "4",
"grade": "X"
}
“等级”属性等于“X”的新对象
{
"ids":{"id":"1","id":"3"}
"engine": "Trident",
"browser": "Internet Explorer 4.0",
"platform": "Win 95+",
"versions":{ "version":"4", "version":"5"}
"grade": "X"
}
我很确定我必须像这样使用$.each和$.grep函数
$.each(dataSet1, function (index, value) {
tsaGrade = dataSet1[index].grade;
result = $.grep(dataSet1, function (e) {
return e.grade == tsaGrade;
})
并将id和版本放在新数组中,但我对如何防止每个循环排除下次循环数据集时已经分组的值感到迷茫.
最佳答案 如果你愿意使用
Underscore.js,这就变得非常微不足道了.
假设数据是json对象的原始列表,这将实现您所追求的目标:
var groups = [];
var by_grade = _.groupBy(data, function(obj) { return obj['grade'] });
_.each(by_grade, function(objs, grade) {
var group = {};
group['grade'] = grade;
group['ids'] = _.pluck(objs, 'id');
group['versions'] = _.pluck(objs, 'version');
// Use the following if the value is known to be
// the same for all grouped objects
group['platform'] = objs[0]['platform'];
// And the rest...
groups.push(group);
});
_.groupBy()将组你的对象的分级,得到与键X和A,其值与相应等级的对象列表的两个对象.然后,您可以遍历两个对象列表中的每一个,提取所需的值,以便将它们作为列表添加到新对象中.很难完全描述,但看到这个Fiddle上的日志消息:)
编辑
相反OBJ文件的[“平台”]应该是使用OBJ文件[0] [“平台”]所有的属性,你知道是与同档次的项目相同.
编辑2
从这个开始,一个更好的方法而不是_.each可能是_.map:
groups = _.map(by_grade, function(objs, grade) {
return {
grade: grade,
browsers: _.pluck(objs, 'browser'),
ids: _.pluck(objs, 'id'),
versions: _.pluck(objs, 'id'),
engines: _.pluck(objs, 'engine')
// etc
}
});