var NameData = ['张三', '李四', '王五', '马六'];
var projectData = ['60米', '3000米', '负重', '100米'];
/*JSON数据分组转化设置*/
function createTree(arr, keys) {
function createObj(arr, arrORobj, keys, start) {
for (let i = 0; i < arr.length; i++) {
if (start >= keys.length) {
let newArray = Array.isArray(arrORobj) ? arrORobj : []
return newArray.concat(arr[i])
}
let curKey = keys[start]
let curVal = arr[i][curKey]
if (!curVal)continue
let newObj = arrORobj[curVal] ? arrORobj[curVal] : {}
arrORobj[curVal] = createObj([arr[i]], newObj, keys, start + 1)
}
return arrORobj
}
return createObj(arr, {}, keys, 0)
}
//按照名字先分组,后按照项目分类,组成新的数组;
var nv = createTree(arr, ['member_name', 'category_name']);
console.log(nv);
//document.write(JSON.stringify(nv));
//document.write("<hr>");
//读取名字;
//document.write(arr[0].member_name);
//document.write("<br>");
//读取转换数组的值;
//document.write(JSON.stringify(nv[1][1][0]['value']));
//document.write(JSON.stringify(nv[NameData[0]]['60米'][0]['value']));
//document.write(JSON.stringify(nv[NameData[0]]['3000米'][0]['value']));
//document.write(JSON.stringify(nv[NameData[0]]['100米'][0]['value']));
//document.write("<hr>");
//判断数据某键值是否存在;
/*
function typeArr(newArr, key) {
if (newArr.hasOwnProperty(key)) {
return nv[NameData[0]][projectData[key]][0]['value'];
} else {
return '0';
}
}
*/
//console.log(JSON.stringify(nv[NameData[0]]['100米'][0]['value']).hasOwnProperty('100米'));
/*判断项目键名中是否为空或未定义*/
function typeArr(newArr, key) {
if (typeof(newArr) == 'undefined' ? false : (newArr.length == 0 ? false : true)) {
return JSON.stringify(nv[NameData[0]][projectData[key]][0]['value']);
} else {
return "0";
}
}
var brr = [];
brr[0] = JSON.stringify(nv[NameData[0]][projectData[0]][0]['value']);
brr[1] = JSON.stringify(nv[NameData[0]][projectData[1]][0]['value']);
brr[2] = typeArr(JSON.stringify(nv[NameData[0]][projectData[2]]), 2);
brr[3] = JSON.stringify(nv[NameData[0]][projectData[3]][0]['value']);
document.write('[' + brr + ']');