[Javascript] Lodash: Refactoring Simple For Loops (_.find, _.findLast, _.filter)

This lesson shows how to refactor your old loops into using a simpler and more powerful lodash-style. We will start by looking at how many people traditionally write JavaScript for loops and then talk about the alternate style and benefits that Lodash offers.

 

If you want to find one value from the value, you can use:

_.find 

or 

_.findLast

 

If you want to get all match results, you can use:

_.filter()

 

var people = [
    {name: "Frank", age: 30, gender: 'male'},
    {name: "Bill", age: 22, gender: 'male'},
    {name: "Carol", age: 52, gender: 'female'},
    {name: "Susan", age: 10, gender: 'female'},
    {name: "Stephanie", age: 22, gender: 'female'},
    {name: "Kyle", age: 68, gender: 'male'},
    {name: "Hank", age: 22, gender: 'male'},
    {name: "Susan", age: 20, gender: 'female'}
];

//Loop: find one 'Susan'
var susan;
for (var i = 0; i < people.length; i++) {
    var person = people[i];
    if(person.name == "Susan"){
        susan = person;
        break;
    }
}

console.log(susan);

//Lodash: find one 'Susan'
var susan2 = _.find(people, {name: 'Susan'});

console.log(susan2);


//Loop: find all 'Susan'
var susans = [];
for (var i = 0; i < people.length; i++) {
    var person = people[i];
    if(person.name == "Susan"){
        susans.push(person);
    }
}

console.log(susans);

//Lodash: find all 'Susan'
var susans2 = _.filter(people, {name: 'Susan'});

console.log(susans2);

 

posted @ 2015-03-21 22:31  Zhentiw  阅读(418)  评论(0编辑  收藏  举报