Skip to content

Instantly share code, notes, and snippets.

@defiant
Created May 29, 2019 15:41
Show Gist options
  • Save defiant/cec2fab35904c814a7e800a11506361b to your computer and use it in GitHub Desktop.
Save defiant/cec2fab35904c814a7e800a11506361b to your computer and use it in GitHub Desktop.
create and object from an array using the given key
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