(npm-link)
object-getvalueGet the Object's property directly including nested properties. It supports the default return value and hasOwnProperty check.
Runtime Error occurs when any key in the sequence is undefined while getting the Object's nested property value.
person.address.location.current.city
To Avoid that, it's best practise to check for each property on object in sequence
if personaddress && personaddresslocation && personaddresslocationcurrent && personaddresslocationcurrentcity // var city = person.address.location.current.city
This package helps you in directly getting the nested property value from the Object
getValue(person, 'address.location.current.city') //=> 'Bangalore'
You can use it to avoid ternary operation while fetching the Object value and assigning that to a variable without worrying about any run-time error.
// Traditional wayvar city = personaddresslocationcurrentcity ? personaddresslocationcurrentcity : 'Bangalore'; // Cleaner & Safe way - using getValue()var city = ;
Installation
npm install object-getvalue --save
Usage
Arguments
object
(Object) The object to queryproperty
(String) Simple or Nested property- (Optional)
defaultValue
(any) The value returned ONLY if property value resolves toundefined
- (Optional)
hasOwnProperty
(bool -default : false
) Checks for the property only on the current object but NOT on Prototype/Parent.
Example
var getValue = ;OR; var { thisname = 'No name defined yet'; thisage = 25; thisaddress = city: 'Default - New Delhi' country: 'Default - India' ;}; var { thisname = 'Ravi Roshan'; thiscompany = 'XYZ Consulting'; thisempId = 12345; thisaddress = city: 'Bangalore' ; thisdetails = role: 'Developer' designation: 'Consultant' domain: 'e-commerce' ; thisfriends = name: 'Siddhant' age: 27 name: 'Harsh' age: 26 name: 'Argha' age: 28 ;}; // Inherit the Person ObjectEmployeeprototype = ; // Create an instance of Employeevar emp1 = ; // Check for property on Current Object //=> 'Ravi Roshan' //=> 'e-commerce' //=> undefined // Check for property on Prototype Object' //=> 25 [Getting from prototype Person Object] //=> undefined // Check for property on Current Object - with Default Return //=> 9999 //=> 'Salary not found' //=> 'Ravi Roshan' [name doesn't resolve to undefined so defaultReturn is not considered] // Check for property ONLY on Current Object //=> 'Age not found' // Check for property on Current OR Prototype Object //=> 25 // Check for the name property on Friends [array] on Emp [object] //=> 'Harsh'
License
MIT