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

179
Visualizações
Check object variable exists when using object destructuring

I have a 'getData' function which gets passed a 'data' variable. Inside the function I'm trying to access an object 'data.someObject' which may or may not exist because it comes from an outside library.

What is the best approach to check if it does exist before trying to use it? Also see I'm using object destructuring here aswell.

const getData = (data) => {
    const { name, age } = data.someObject; // someObject may or may not exist
    console.log(name, age);
}

I thought doing this might work:

const { name, age } = data.someObject || {};

But I wasn't sure if that would throw an error.

Thanks

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

0

Personally I would put an if statement:

const getData = (data) => {
  if (data.someObject == null) {
    // Here you can return, throw an error or do anything else you might need
  }
  const { name, age } = data.someObject; // someObject may or may not exist
  console.log(name, age);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use || & if required provide default values while destructuring.

function print(user) {
  const { fname = "Anonymous", lname = "Panda" } = user.fullname || {};

  console.log(`Hello ${fname} ${lname}`);
}

print({ fullname: { fname: "John", lname: "Doe" } });
print({});
print({ fullname: null });

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