Last active
April 19, 2016 11:31
-
-
Save alexandrricov/13f86fd34cee9ae104ca7fae1e9402c7 to your computer and use it in GitHub Desktop.
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
/** | |
* | |
* @param {Object} obj - base object | |
* @param {string} prop - property path | |
* @returns {*} | |
*/ | |
function getProperty(obj, prop) { | |
return prop.split('.') | |
.reduce((m, i) => m && typeof m === 'object' ? m[i] : null, obj); | |
} | |
/** | |
* | |
* @param {Array} itemList - base array | |
* @param {string|Array<string>} pluckStrings - path or path array | |
* @returns {Array} | |
*/ | |
function pluck(itemList, pluckStrings) { | |
const pathList = Array.isArray(pluckStrings) ? pluckStrings : [pluckStrings]; | |
return itemList.reduce( | |
(items, item) => { | |
for (let i = 0; i < pathList.length; i++) { | |
const path = pathList[i].trim(); | |
const prop = getProperty(item, path); | |
if (prop) { | |
return items.concat(prop); | |
} | |
} | |
return items; | |
}, | |
[] | |
); | |
} | |
let users = [ | |
{name: 'Victor Queiroz'}, | |
{name: 'João Bosco'}, | |
{nickname: {myNickname: 'Ruan Jordão'}} | |
]; | |
pluck(users, ['name', 'nickname.myNickname']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment