Skip to content

Instantly share code, notes, and snippets.

@ozantunca
Last active August 29, 2015 13:57
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 ozantunca/9740214 to your computer and use it in GitHub Desktop.
Save ozantunca/9740214 to your computer and use it in GitHub Desktop.
An underscore.js mixin for picking nested properties by keeping the nested structure.
_.mixin({
nestedPick: function (obj, wantedKeys) {
var resultObj = {};
_.forEach(wantedKeys, function (key) {
// Parsing nested keys. Making it so that a[b] equals a.b
var nestedKeys = key.replace(/\[(["']?)([^\1]+?)\1?\]/g, '.$2').replace(/^\./, '').split('.')
, finalVal = {}
, dummy = {}
, recVal = obj[nestedKeys[0]]
, j = 1
, nestedVal;
if(nestedKeys.length == 1) {
resultObj[key] = obj[key];
return;
}
// Receive nested value
while(_.isUndefined(recVal) && j < nestedKeys.length) {
nestedVal = recVal;
recVal = recVal[nestedKeys[j++]];
}
// Continue looping value is not present
if(_.isUndefined(recVal))
return;
else {
// Build nested value
nestedVal = recVal;
finalVal[_.last(nestedKeys)] = nestedVal;
for(var i = nestedKeys.length-2; i > 0; i--) {
dummy[nestedKeys[i]] = finalVal;
finalVal = dummy;
}
}
// Add value to the final object
resultObj[nestedKeys[0]] = finalVal;
});
return resultObj;
}
});
// Example Object
var user = {
accounts: {
facebook: {
email: 'foo@example.com',
username: 'foobar',
accessToken: 'secretSauce'
},
twitter: {}
},
password: 'secretSauce',
totalLikes: 1234
}
// Example Usage
var filteredUser = _.nestedPick(user, ['accounts.facebook.email', 'totalLikes']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment