2

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

3
  • no need to use any library, you can use personsDetails?.[1]?.name instead of personsDetails && personsDetails[1] && personsDetails[1].name. this is optional chaning (?.) developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 1, 2022 at 5:14
  • @MohitSharma the project which i have is running a very old version of node, so optional chaining is not supported, and we dont want to change the webpack currently due to some reasons, so with already installed lodash, i want to get it work if its possible or maybe any other way which works on node 13 :) Commented Jul 1, 2022 at 5:21
  • 1
    "As far as i know _get property works with object only so here i am dealing with array and then object" 1. Arrays are objects. 2. Lodash does also explicitly support syntax for accessing arrays anyway. Commented Jul 1, 2022 at 5:23

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.