Underscore Find Object in Collection

by mrrodd

JavaScript

var statesColl = [
    {"Name": "AZ", Count: 2},
    {"Name": "CA", Count: 3},
    {"Name": "TX", Count: 1}
];

console.log(statesColl);

var filter = "AZ";

// Check if the current state is already in the collection0
var state = _.find(statesColl, function(item) {
    return item.Name == filter; 
});

// Add the state to the collection if it does not exist
// otherwise increment the state count
if( state == undefined) {   
    statesColl.push({"Name": "YZ", "Count": 1});
} else {
    state.Count = parseInt(state.Count) + 1;
}

console.log(statesColl);