javascript - 将数据推送到两级数组上

标签 javascript arrays

有人知道或给我一些关于如何填充多维数据数组的指导吗: 我有一个数据数组:

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}
];

我需要使用以下格式的数据填充该二维数组:

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
    }]
}];

提前致谢...

最佳答案

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
    });

});

http://jsfiddle.net/8Zke8/2/

关于javascript - 将数据推送到两级数组上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22030433/

相关文章:

java - 如何识别两个不同输出中的相同数字

c++ - 用更少的内存在 C++ 中实现二维数组

javascript - 渲染不同组件时无法更新组件 (`App` )

javascript - 填充背景颜色,然后叠加一个PNG

java - 将二维数组从行转换为 block

arrays - 简化使用数组填充变量

python - 在Stata中高效处理矩阵

javascript - bootstrap.css 和 IE11 问题

javascript - 在 D3 map 上的纬度和经度点之间添加静态线

javascript - React Plotly JS 应用深色(plotly_dark)主题