Last active
December 16, 2020 01:21
-
-
Save nyk0r/3da589b3dc97d1833c140cb1dd6cd652 to your computer and use it in GitHub Desktop.
array to table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'] | |
]; | |
const createSetter = (name, idx) => (dst, src) => ({ | |
...dst, | |
[name]: src[idx], | |
}); | |
const createSetters = (cols) => cols.map((name, idx) => createSetter(name, idx)); | |
const applySetters = (setters, row) => | |
setters.reduce( | |
(r, s) => s(r, row), | |
{} | |
); | |
const arr2objs = (arr) => { | |
const [cols, ...rows] = arr; | |
const setters = createSetters(cols); | |
return rows.map((row) => applySetters(setters, row)); | |
}; | |
console.log(arr2objs(arr1)); | |
console.log(arr2objs(arr2)); | |
console.log(arr2objs(arr3)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment