Skip to content

Instantly share code, notes, and snippets.

@moekhalil
Last active June 21, 2023 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moekhalil/5a3567fbaa3689b09dd2e92150bbe1f6 to your computer and use it in GitHub Desktop.
Save moekhalil/5a3567fbaa3689b09dd2e92150bbe1f6 to your computer and use it in GitHub Desktop.
Just playing with how a native Array.prototype.mapKey would look.
/**
*
* @name: Array.prototype.mapKey
* @author: @moekhalil (GitHub)
*
* @description: A prototype of a native Array.prototype.mapKey that
* would allow users to map over an array of objects
* and return the value of a specific key or nested key
*
* @param prop {string | string[] | function}
* @returns {any[]}
*/
Array.prototype.mapKey = function (prop) {
if (typeof prop === 'string') {
return this.map((item) => item[prop]);
}
if (Array.isArray(prop)) {
if (prop.length === 1) {
return this.map((item) => item[prop[0]]);
}
return this.map((item) =>
prop.reduce((o, key) => (o ? o[key] : void 0), item)
);
}
if (typeof prop === 'function') {
return this.map(prop);
}
if (typeof prop === 'undefined') {
throw new Error(
'mapKey requires a property name, array of property names, or function'
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment