shrewdbeans
shrewdbeans

Reputation: 12529

JavaScript: Error when destructuring an array of objects when the array is empty

What is the cleanest way of getting around this scenario?

Considering I have an array of objects:

let originalArray = [{
  personName: 'Ben'
}];

I can destructure like this:

const [{
  personName: name
}] = originalArray;

console.log(name); // "Ben"

However, if originalArray is empty...

let originalArray = [];

const [{
  personName: name
}] = originalArray;

I get this error

Uncaught TypeError: Cannot destructure property `personName` of 'undefined' or 'null'

I've found some articles/docs explaining how to handle errors when destructuring just an object, but not if it's an array of objects, and the array is empty.

Upvotes: 5

Views: 5778

Answers (3)

Azad
Azad

Reputation: 5264

You can set a default value

var [{ personName: name = 'default' } = {}] = [{ personName: 'Ben' }];
console.log(name);

var [{ personName: name = 'default' } = {}] = [];
console.log(name);

Upvotes: 2

feralonsomaccari
feralonsomaccari

Reputation: 26

You should declare the array like this. So it will be an empty array of object by default. Otherwise will throw that error.

let originalArray = [{}];

You can also declare a default value if you know how many properties you will have.

let originalArray = [];

const [{
 personName: name = 'ben',
 personAge: age = '23'
} = {}] = originalArray;

console.log(name); // "Ben"
console.log(age); // "23"

Upvotes: 0

Abito Prakash
Abito Prakash

Reputation: 4770

You can set default values for undefined properties

const [{
  personName: name = ''
} = {}] = originalArray;

console.log(name); // ""

Upvotes: 6

Related Questions