Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
Lodash to check object property on array elements

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda