Skip to content

Instantly share code, notes, and snippets.

@moekhalil
Last active September 20, 2024 23:18
Show Gist options
  • Select an option

  • Save moekhalil/5a3567fbaa3689b09dd2e92150bbe1f6 to your computer and use it in GitHub Desktop.

Select an option

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[]}
* @returns {any[]}
*/
Array.prototype.mapKey = function (prop) {
if (typeof prop === 'string') {
return this.map((item) => item[prop]);
}
if (Array.isArray(prop)) {
return this.map((item) =>
prop.reduce((o, key) => item.hasOwnProperty(key)
? ({ ...o, [key]: item[key] })
: o
, {})
);
}
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