有人知道或给我一些关于如何填充多维数据数组的指示: 我有一个数据数组:
dataTable = [
{section: 'section1', item: 'item1', num: 0},
{section: 'section2', item: 'item1', num: 0},
{section: 'section3', item: 'item1', num: 0},
{section: 'section3', item: 'item2', num: 0}
];
我需要使用以下格式填充该数据的2D数组:
tableToLoad = [{
sectionNum: 1,
sectionTitle: "section1",
data: [{
level: 1,
title: item1,
child: false
}]
}, {
sectionNum: 2,
sectionTitle: "section2",
data: [{
level: 1,
title: item1,
child: false
}]
}, {
sectionNum: 3,
sectionTitle: "section3",
data: [{
level: 1,
title: item1,
child: false
}, {
level: 1,
title: item2,
child: false
}]
}];
提前致谢...
答案 0 :(得分:1)
var tableToLoad = [], tableSecIdx = {};
dataTable.forEach(function(item) {
//find the sec index
var idx = tableSecIdx[item.section];
if (!idx) {
//push a new one
tableToLoad.push({
sectionNum : tableToLoad.length + 1,
sectionTitle : item.section,
data : []
});
//remember the idx
tableSecIdx[item.section] = idx = tableToLoad.length - 1;
}
//push the data
tableToLoad[idx].data.push({
level : 1,
title : item.item,
child : false
});
});
答案 1 :(得分:1)
尝试以下方式:
var tableToLoad = [], dataMap = {};
for (var i = 0; i < dataTable.length; i++) {
var data = dataTable[i];
if (dataMap[data.section]) {
dataMap[data.section].data.push({
level: 1,
title: data.item,
child: false
});
continue;
}
var newData = {
sectionNum: tableToLoad.length + 1,
sectionTitle: data.section,
data: [{
level: 1,
title: data.item,
child: false
}]
};
dataMap[data.section] = newData;
tableToLoad.push(newData);
}