Created
May 29, 2019 15:41
-
-
Save defiant/cec2fab35904c814a7e800a11506361b to your computer and use it in GitHub Desktop.
create and object from an array using the given key
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 objectifyByKey(arr, key) { | |
if (!Array.isArray(arr)) throw new Error('not an array'); | |
if (!arr.length) return; | |
const reducer = (acc, el) => { | |
if (Object.prototype.hasOwnProperty.call(key, el)) { | |
return { ...acc, [el[key]]: el }; | |
} | |
return {}; | |
}; | |
return arr.reduce(reducer, {}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment