Skip to content

Instantly share code, notes, and snippets.

@nfeldman
Created September 24, 2011 03:38
Show Gist options
  • Save nfeldman/1238920 to your computer and use it in GitHub Desktop.
Save nfeldman/1238920 to your computer and use it in GitHub Desktop.
pluck an object from an array
/**
* 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
}
/**
* 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