Last active
August 3, 2020 08:39
-
-
Save matsub/764c1d2082f95e7e67a0e0341292e5d0 to your computer and use it in GitHub Desktop.
convert a serial array to an object in JavaScript and TypeScript
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
function objectify(arr) { | |
return Object.fromEntries(arr.reduce((acc, cur, idx) => (idx%2 ? acc[acc.length-1].push(cur) : acc.push([cur])) && acc, [])); | |
} |
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
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