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

246
Visualizações
How to add optional chaining to JSON object?

I am trying to compare a value within a JSON object with a variable:

if (resp.userdetails.name == username) {
// do something
}

The problem is that not all resp objects have userdetails, so I get this error message sometimes:

Cannot read properties of undefined (reading 'name')

I have tried to use ? to say it might be optional (or not exist):

if (resp.userdetails?.name == username)

But I get an Unexpected token error in that case.

Can someone please tell me how I can update my if statement to say userdetails may not always be in the response, but if it is, then check name is equal to username?

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

0

Either:

  • Use a JS engine which supports optional chaining
  • Use a tool like Babel to transpile your JS from a modern version of the language to an older one which doesn't support optional chaining
  • Manually test for the object existing before you try to read a property from it
if (resp.userdetails && resp.userdetails.name == username)

about 4 years ago · Juan Pablo Isaza Relatório

0

If you installed lodash into your project, then you can use

_.get(resp,"userdetails.name")

as documented.

If you haven't installed lodash, then I strongly suggest you install from npm because lodash is the best and the most widely used utility package.

about 4 years ago · Juan Pablo Isaza Relatório

0

Lodash is a popular javascript based library which provides 200+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on. Lodash can be used directly inside a browser and also with Node.js.

Working with objects using JavaScript can be quite challenging, specifically if you have lots of manipulation to be done with them. Lodash comes with lots of features that eases your work with objects.

Lodash is an open source project and you can easily contribute to the library and add features in the form of plugins and make it available on GitHub and in Node.js.

Syntax

_.get(object, path, [defaultValue]) Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

Arguments

object (Object) − The object to query.

path (Array|string) − The path of the property to get.

[defaultValue] (*) − The value returned for undefined resolved values.

If you installed lodash into your project, then you can use

_.get(resp,"userdetails.name")

as documented.

If you haven't installed lodash, then I strongly suggest you install from npm because lodash is the best and the most widely used utility package.

command to install Lodash

npm install loadash

enter image description here Eg:-

  var _ = require("lodash");

var data = [
  { userdetails: { name: "d" } },
  {},
  { userdetails: {} },
  { userdetails: { name: "d" } },
];

for (i = 0; i < data.length; i++) {
  var resp = data[i];
  if (_.get(resp, "userdetails.name") == "d") {
    //   if (resp.userdetails && resp.userdetails.name == "d") {    use without loadlash
    console.log("Success");
  } else {
    console.log("failed");
  }
}

Here loadash is super complex. But you can use this to avoid runtime errors. Below both expressions get the same result

   resp.userdetails && resp.userdetails.name == "d"

                        ===

         _.get(resp, "userdetails.name") == "d"
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