Skip to content

Instantly share code, notes, and snippets.

@nyk0r
Last active December 16, 2020 01:21
Show Gist options
  • Save nyk0r/3da589b3dc97d1833c140cb1dd6cd652 to your computer and use it in GitHub Desktop.
Save nyk0r/3da589b3dc97d1833c140cb1dd6cd652 to your computer and use it in GitHub Desktop.
array to table
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