我有一些动态生成的JSON数据,我需要按特定的数字进行分组。所以我有办法为数字生成变量,但需要根据该数字对项目进行分组。这是原始的JSON:
"items":[
{"name":"School","value":"sdf"},
{"name":"Year","value":"dsf"},
{"name":"GPA","value":"Sdfdsf"},
{"name":"School","value":"sdf"},
{"name":"Year","value":"dsf"},
{"name":"GPA","value":"Sdfdsf"},
]
我需要按照每3个项目进行分组,格式如下:
"items":[
"item":{
"School":"sdf",
"Year":"dsf",
"GPA":"Sdfdsf"
},
"item":{
"School":"sdf",
"Year":"dsf",
"GPA":"Sdfdsf"
}
]
这是我目前的代码:
var newData = "items": [];
jQuery('.dynamicRow input').each(function() {
var dName = jQuery(this).closest('input').attr('name');
var dValue = jQuery(this).closest('input').val();
var obj = {
name: dName,
value: dValue
};
newData.items.push(obj);
});
jQuery('#debug').text(JSON.stringify(newData));
答案 0 :(得分:2)
如果var data = { "items": [{ "name": "School", "value": "sdf" }, { "name": "Year", "value": "dsf" }, { "name": "GPA", "value": "Sdfdsf" }, { "name": "School", "value": "sdf" }, { "name": "Year", "value": "dsf" }, { "name": "GPA", "value": "Sdfdsf" }] },
result = {
items: data.items.reduce(function (r, a, i) {
if (!(i % 3)) {
r.push({});
}
r[r.length - 1][a.name] = a.value;
return r;
}, [])
};
console.log(result);
为零,您可以使用Array#reduce
并插入新对象。
在项目的最后一个元素添加属性。
.as-console-wrapper { max-height: 100% !important; top: 0; }

{{1}}