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);
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();
}