2

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.