ikiw
ikiw

Reputation: 358

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

Upvotes: 0

Views: 36

Answers (1)

pilchard
pilchard

Reputation: 12918

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

Upvotes: 1

Related Questions