I want to use lodash to find a property of an object at a specific array element.
Lets say I am hitting an api and getting response which sets it to the react state “personsDetails” (whose initial value was null), so now it becomes
let personsDetails=[{name:'king',id:2},{name:'queen',id:3}] //sometimes i get 1 object and sometimes 2
now when i want to access “name” property of 2nd object i do
personsDetails && personsDetails[1] && personsDetails[1].name
So is there any shorted syntax of accessing it via using lodash ? If the values doesnt exist i need null
As far as i know _get property works with object only so here i am dealing with array and then object
Advertisement
Answer
You can still use get
and set the default as null
let personsDetails=[{name:'king',id:2},{name:'queen',id:3}] let res = _.get(personsDetails, '1.name',null) //or _.get(personsDetails, '[1].name',null) console.log(res) console.log(_.get(undefined, '1.name',null)) console.log(_.get([], '1.name',null))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
or can use nth
along with get
and set the default as null
let personsDetails=[{name:'king',id:2},{name:'queen',id:3}] let res = _.get(_.nth(personsDetails,1),'name',null) console.log(res) console.log(_.get(_.nth([],1),'name',null)) console.log(_.get(_.nth(undefined,1),'name',null))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>