Problem
We need to merge all this arrays into one big object.
First line of every array is the table headings, followed by users data.
const arr1 = [ ["name", "id", "age", "weight", "Cool"], ["Susan", "3", "20", "120", true], ["John", "1", "21", "150", true], ["Bob", "2", "23", "90", false], ["Ben", "4", "20", "100", true], ]; const arr2 = [ ["name", "id", "height"], ["Bob", "2", "50"], ["John", "1", "45"], ["Ben", "4", "43"], ["Susan", "3", "48"] ]; const arr3 = [ ["name", "id", "parent"], ["Bob", "2", "yes"], ["John", "1", "yes"] ];
My proposal:
const data = {}; function addData(arr, uuid = 'id'){ const [headings, ...body] = arr; for(const elem of body){ let id; let person = {}; for(const [index, heading] of headings.entries()){ if(heading === uuid){ id = elem[index]; } person[heading] = elem[index]; } data[id] = {...data[id], ...person}; } } addData(arr1); addData(arr2); addData(arr3); console.table(data);
Can you improve it? Do you have a different solution?
Let me know in comments!
Top comments (1)
I used the same names for variables. I don't like messing with global variables very much, so I made a
makeData()
function, which is a pure function.Then I made a replacement
addData()
function to have the same functionality as your code. You can use it the same way 😄