Skip to content

Instantly share code, notes, and snippets.

@alexandrricov
Last active April 19, 2016 11:31
Show Gist options
  • Save alexandrricov/13f86fd34cee9ae104ca7fae1e9402c7 to your computer and use it in GitHub Desktop.
Save alexandrricov/13f86fd34cee9ae104ca7fae1e9402c7 to your computer and use it in GitHub Desktop.
/**
*
* @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