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

160
Visualizações
Object destructuring: Assign null values in one line

Assuming I have an object like this

foo = {
    a: 1,
    b: 2,
    c: 3
};

I would destructure it this way

const {a, b, c} = foo;

However, what, if the keys a, b and c do not exist?

foo = null;

This won't work then

const {a, b, c} = foo;

I would have to do something like

let a, b, c;

if(foo) {
    a = foo.a;
    b = foo.b;
    c = foo.c;
};

Is there a way to do this in one line? Something like

 const {a, b, c} = foo ? foo : null; // this is not working

null is not an object. (evaluating '_ref2.a')

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

0

When foo is not an object, you are going to have to give it an object so the destructuring can happen. So set it to an empty object using an 'or'. Now if foo is defined it will use foo, if it is not defined it will use the default object.

const foo = undefined;
const { a, b, c } = foo || {};
console.log(a, b, c);

If you want default values, set them in the object.

const foo = undefined;
const { a, b, c } = foo || {a : 'a', b: 'b', c: 'c' };
console.log(a, b, c);

If you want default values if the object does not provide them all, you can set values in the destructuring.

const foo = { a: 1};
const { a = "a", b = "b", c = "c" } = foo || {};
console.log(a, b, c);

about 4 years ago · Juan Pablo Isaza Relatório

0

What about destructuring default parameters? If foo could be undefined set = foo || {} in destructuring to avoid exception

let foo = {};
const {a = null, b = null, c = null} = foo;

console.log('a:', a);
console.log('b:', b);
console.log('c:', c);

about 4 years ago · Juan Pablo Isaza Relatório

0

It will work like you might expect, the variables a b and c will be created with the value of undefined. this is the fallback when also trying to access a property which doesn't exist on a certain object.

const foo = {};
console.log(foo.a); // undefined

const {a, b, c} = foo;

console.log(a); // undefined
console.log(b); // undefined

console.log(d); // Uncaught ReferenceError: d is not defined

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