Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!