Skip to content
This repository has been archived by the owner on Dec 24, 2023. It is now read-only.

puttyman/js-tips-and-life-hacks-using-lodash

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

Javascript tips and life hacks with lodash

Retriving a value from a nested object using _.get()

Given the following object:

let request = {
  person: {
    address: {
      postcode: '3000'
    }
  }
}

Avoid:

var postcode = 3000; // default postcode
if(request && request.person && request.person.address && request.person.address.postcode) {
    postcode = request.person.address.postcode;
}

Do:

var postcode = _.get(request, 'person.address.postcode', 3000);

Checking if object has a set of keys using _.has()

Given:

let person = {
    address: {},
    age: 100,
    weight: 77,
    name: 'Tom',
    skills: ['js', 'java', 'c++']
  }

Avoid:

if(person.address && person.age && person.weight && person.name) {
    person.save();
}

Do:

if(_.has(person, ['address', 'age', 'weight']) {
    person.save();
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published