Last active
August 29, 2015 13:57
-
-
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.
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
_.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; | |
} | |
}); |
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
// 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