[Javascript] Lodash:refactoring Simple for Loops (_.find, _.findlast, _.filter)

Source: Internet
Author: User

This lesson shows how to refactor your old loops into using a simpler and more powerful lodash-style. We'll start by looking at what many people traditionally write JavaScript loops and then talk about the for alternate s Tyle 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 ()

varPeople =[{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 'varSusan; for(vari = 0; i < people.length; i++) {    varperson =People[i]; if(Person.name = = "Susan") {Susan=Person ;  Break; }}console.log (Susan);//lodash:find One ' Susan 'varSusan2 = _.find (People, {name: ' Susan ')}); Console.log (susan2);//loop:find all ' Susan 'varSusans = []; for(vari = 0; i < people.length; i++) {    varperson =People[i]; if(Person.name = = "Susan") {Susans.push (person); }}console.log (Susans);//lodash:find all ' Susan 'varSusans2 = _.filter (People, {name: ' Susan ')}); Console.log (SUSANS2);

[Javascript] Lodash:refactoring Simple for Loops (_.find, _.findlast, _.filter)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.