简体   繁体   中英

Transforming multi-dimensional array into grouped array of objects

I have a multidimensional array as below (columns) and need it transformed into array of objects forming a grouped hierarchal structure to construct a table header.

Each values has to be nested in the order of index and also grouped. Any pointers how this can be achieved?

var columns = [
        ["Price", "Australia", "Melbourne", "Comfort Hotel & Spa"],
        ["Price", "Costa Rica", "Tamarindo", "Summer Isle Hotel"],
        ["Stars", "Fiji", "Suva", "Crescent Resort1"],
        ["Stars", "Fiji", "Suva", "Crescent Resort2"],
    ];

//need it to be transformed into structure like this
var transformedArray = [{
    Header: 'Price',
    columns: [{
        Header: 'Australia',
        columns: [{
            Header: 'Melbourne',
            columns: [{
                Header: 'Comfort Hotel & Spa',
                value: 'Price-Australia-Melbourne-Comfort Hotel & Spa'
            }]
        }]
    }, {
        Header: 'Costa Rica',
        columns: [{
            Header: 'Tamarindo',
            columns: [{
                Header: 'Summer Isle Hotel',
                value: 'Price-Costa Rica-Tamarindo-Summer Isle Hotel'
            }]
        }]
    }]
}, {
    Header: 'Stars',
    columns: [{
        Header: 'Fiji',
        columns: [{
            Header: 'Suva',
            columns: [{
                    Header: 'Crescent Resort1',
                    value: 'Stars-Fiji-suva-Crescent Resort1'
                },
                {
                    Header: 'Crescent Resort2',
                    value: 'Stars-Fiji-suva-Crescent Resort2'
                }
            ]
        }]
    }]
}]

You can use nested reduce() calls to build the structure of each object, reserving out the last element of each array to push into the innermost columns array returned by the inner reduce()

 var input = [["Price", "Australia", "Melbourne", "Comfort Hotel & Spa"], ["Price", "Costa Rica", "Tamarindo", "Summer Isle Hotel"], ["Stars", "Fiji", "Suva", "Crescent Resort1"], ["Stars", "Fiji", "Suva", "Crescent Resort2"],]; const output = input.reduce((a, arr) => { const leafValue = arr.join('-'), leafHeader = arr.pop(); const inner = arr.reduce((b, e) => ( b.push({ Header: e, columns: [] }), b[b.length - 1].columns), a) inner.push({ Header: leafHeader, value: leafValue }); return a; }, []) console.log(JSON.stringify(output, null, 2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM