Skip to content

Instantly share code, notes, and snippets.

@matsub
Last active August 3, 2020 08:39
Show Gist options
  • Save matsub/764c1d2082f95e7e67a0e0341292e5d0 to your computer and use it in GitHub Desktop.
Save matsub/764c1d2082f95e7e67a0e0341292e5d0 to your computer and use it in GitHub Desktop.
convert a serial array to an object in JavaScript and TypeScript
function objectify(arr) {
return Object.fromEntries(arr.reduce((acc, cur, idx) => (idx%2 ? acc[acc.length-1].push(cur) : acc.push([cur])) && acc, []));
}
interface LooseObject {
[key: string]: string;
}
export function objectify(array: Array<string>): LooseObject {
const result: LooseObject = {};
const length = array.length;
for (let i = 1; i < length; i += 2) {
result[array[i-1]] = array[i];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment