function to lookup object(s) in array of object based on one of the properties
Note: this is the same as Underscore's _.where() with a single object for the criteria. But _.where is more capable because you can filter on multiple props
by Spencer Wasden
July 01, 2015
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
JavaScript
var columns = [
{
field: 'ID',
hidden: true
},
{
label: 'First Name',
field: 'FirstName',
width: '55%',
hidden: true
},
{
name: 'Last Name',
field: 'LastName',
width: '45%'
}
];
function lookup(array, prop, value) {
var ret = [];
for (var i = 0, len = array.length; i < len; i++){
if (array[i][prop] === value){
ret.push(array[i]);
}
}
return ret;
}
// these 2 are the same
var hidden = lookup(columns, 'hidden', true);
var _hidden = _.where(columns, {hidden: true});
// underscore can do more though, querying on multiple properties
var _hiddenMlt = _.where(columns, {hidden: true, field: 'FirstName'});
console.log( JSON.stringify(hidden) );
console.log( JSON.stringify(_hidden) );
console.log( JSON.stringify(_hiddenMlt) );