我想把一个有规律的数组转成json对象的数组呢,如下:
数组
[
"3040131111",
"小明",
"1",
"大学体育Ⅰ",
"通识课",
"2.00",
"75",
"总评成绩",
"2.50",
"A16603001A",
"32.00",
"3040133109",
"小明",
"1",
"基础英语Ⅰ",
"通识课",
"4.00",
"80",
"总评成绩",
"3.00",
"A17001021A",
"64.00"
]
转成这种
[
{
"学号": "3040111111",
"姓名": "小明",
"学期": "1",
"课程": "大学体育Ⅰ",
"类别": "通识课",
"学分": "2.00",
"成绩": "75",
"成绩类型": "总评成绩",
"绩点": "2.50",
"课程彪悍": "A16603001A",
"课时": “32.00”
},
{
"学号": "3040111111",
"姓名": "小明",
"学期": "1",
"课程": "大学体育Ⅰ",
"类别": "通识课",
"学分": "2.00",
"成绩": "75",
"成绩类型": "总评成绩",
"绩点": "2.50",
"课程彪悍": "A16603001A",
"课时": “32.00”
}
]
用什么方法去做呢?
伊谢尔伦2017-04-17 11:47:49
php
function array_chunk(input, size, preserve_keys) { var x, p = '', i = 0, c = -1, l = input.length || 0, n = []; if (size < 1) { return null; } if (Object.prototype.toString.call(input) === '[object Array]') { if (preserve_keys) { while (i < l) { (x = i % size) ? n[c][i] = input[i] : n[++c] = {}, n[c][i] = input[i]; i++; } } else { while (i < l) { (x = i % size) ? n[c][x] = input[i] : n[++c] = [input[i]]; i++; } } } else { if (preserve_keys) { for (p in input) { if (input.hasOwnProperty(p)) { (x = i % size) ? n[c][p] = input[p] : n[++c] = {}, n[c][p] = input[p]; i++; } } } else { for (p in input) { if (input.hasOwnProperty(p)) { (x = i % size) ? n[c][x] = input[p] : n[++c] = [input[p]]; i++; } } } } return n; } arr = [ "3040131111", "小明", "1", "大学体育Ⅰ", "通识课", "2.00", "75", "总评成绩", "2.50", "A16603001A", "32.00", "3040133109", "小明", "1", "基础英语Ⅰ", "通识课", "4.00", "80", "总评成绩", "3.00", "A17001021A", "64.00" ]; arr_chunk = array_chunk(arr,11).map(function(i){ return { "学号": i[0], "姓名": i[1], "学期": i[2], "课程": i[3], "类别": i[4], "学分": i[5], "成绩": i[6], "成绩类型":i[7], "绩点": i[8], "课程彪悍": i[9], "课时": i[10] } }); console.log(arr_chunk);
怪我咯2017-04-17 11:47:49
Your keys are all the same and can be saved as an array. Get your original data every 11, then traverse the object by key and value respectively, and finally push it into the result array.
PHP中文网2017-04-17 11:47:49
Use Underscore
The code is as follows
var label = ["学号","姓名","学期","课程","类别","学分","成绩","成绩类型","绩点","课程彪悍","课时"],
arr = ***;
_.map([_.head(arr), _.tail(arr)], function(arr){
return _.object(label, arr);
});