cheziHoyzer
cheziHoyzer

Reputation: 5041

Javascript - nested arrays by flat object

I have object with metadata regarding the table (row and column) position

 {a:{row:0,col:0,data:{}},b:{row:1,col:0,data:{}},c:{row:1,col:1,data:{}},d:{row:2,col:0,data:{}},e:{row:2,col:1,data:{}}}

I want to reorder the object to iterate and render it as a table (I'm using React but it's not important).
So my final object should be like this:

 [[{key:"a",data:{}}],[{key:"b",data:{}},{key:"c",data:{}}],[{key:"d",data:{}},{key:"e",data:{}}]]

I tried (a lot) to do it elegant and nicely without any success (the result was too many for loops), I believe there is some elegant way to achieve it.

Upvotes: 2

Views: 45

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386680

Just reduce the entries and take row/col as target for a nested array.

var data = { a: { row: 0, col: 0, data: {} }, b: { row: 1, col: 0, data: {} }, c: { row: 1, col: 1, data: {} }, d: { row: 2, col: 0, data: {} }, e: { row: 2, col: 1, data: {} } },
    result = Object.entries(data).reduce((r, [key, { row, col, data }]) => {
        r[row] = r[row] || [];
        r[row][col] = { key, data };
        return r;
    }, []);

console.log(result);

Upvotes: 1

Related Questions