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

147
Visualizações
javascript object destructuring one line with nulls or nullable keys

when destructuring object in js & it has some value which is null then destructuring is failing with error Cannot read property 'id' of null

const abc = {a: 1, b: 2, c: null};
let {c = {}, c: {id} = {}} = abc || {};
console.log('c, id', c, id);

in case value of a key is null, js throws an exception. we dont know which key is nullable. I want this to be handled in a single line like normal destructuring. is it possible. for this example sake, make into two lines first check if c is null but I want to do it one line.

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

0

The default value in destructuring will only work for undefined properties and not null

From MDN

A variable can be assigned a default, in the case that the value unpacked from the object is undefined

const abc = {a: 1, b: 2, c: undefined};
let {c = {}, c: {id} = {}} = abc || {};
console.log('c, id', c, id);

For c: null, you'd have to use:

let id = abc.c?.id
about 4 years ago · Juan Pablo Isaza Relatório

0

Not the best way to do but, I have got an idea to convert nulls to undefined before destructuring so that, js will take care of taking the default values.

here is the working code

function removeNulls(obj) {
if (obj === null) {
    return undefined;
}
if (typeof obj === 'object') {
    for (let key in obj) {
        obj[key] = removeNulls(obj[key]);
    }
}
return obj;
}
const abc = {a: 1, b: 2, c: null};
let {c = {}, c: {id, id2} = {}} = removeNulls(abc) || {};
console.log('c, id, id2:', c, id, id2);

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