Last active
June 21, 2023 16:11
-
-
Save moekhalil/5a3567fbaa3689b09dd2e92150bbe1f6 to your computer and use it in GitHub Desktop.
Just playing with how a native Array.prototype.mapKey would look.
This file contains 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
/** | |
* | |
* @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