Created
September 24, 2011 03:38
-
-
Save nfeldman/1238920 to your computer and use it in GitHub Desktop.
pluck an object from an array
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
/** | |
* required by pluckObjectByKey can be handy if you're dealing with JavaScript written by Java devs | |
* they like long.strings.with.dots.in.them. | |
*/ | |
function getNestedObject (obj, path) { | |
var nest, len; | |
if (path) { | |
nest = path.split('.').reverse(); | |
len = nest.length; | |
while (len--) { | |
if (obj[nest[len]]) | |
obj = obj[nest[len]]; | |
else | |
return false | |
} | |
return obj | |
} | |
return false | |
} |
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
/** | |
* Recently found myself needing something like this several times | |
* @author Noah Feldman | |
*/ | |
function pluckObjectByKey (name, value, collection, filter) { | |
var i = collection.length, | |
firstDot = name.indexOf('.'), | |
lastDot, nested, ret, path; | |
if (firstDot > -1) { | |
lastDot = name.lastIndexOf('.'); | |
if (firstDot != lastDot) { | |
path = name.slice(0, lastDot); | |
name = name.slice(++lastDot); | |
nested = true; | |
} else { | |
name = name.split('.'); | |
path = name[0]; | |
name = name[1]; | |
nested = false; | |
} | |
} else { | |
path = name; | |
nested = false; | |
} | |
if (!filter) | |
filter = function (x) { return x }; | |
while (i--) { | |
obj = nested ? getNestedObject(collection[i], path) : collection[i][path]; | |
if (filter(obj[name]) === value) | |
return { index: i, result: collection[i] }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment