I have an object like this
const obj = [{a: 'a'}];
I can get it like: const { a } = obj[0]; //a
const { a } = obj[0]; //a
but what if obj['x'] doesn't exist?
I tried this with optional chainning but doesn't seem to work. const { a } = obj?.[1];
You can use the Logical OR operator .
const { a } = obj[x] || {}
If obj
does not have a property x
, a
will be set to undefined
.
You are close to it. You should make sure to fallback with an empty object, for the destructing later to make sense
const obj = [{a: 'a'}]; const { a } = obj?.[1] || {}; console.log(a)
Update
This would be even shorter if you don't use destructing in this case
const obj = [{a: 'a'}]; const a = obj?.[1]?.a; // or: obj?.[1]?.['a'] console.log(a)
You could festructure with an index as computed property and a default object for a missing item of the array.
const obj = [{ a: 'a' }], { [2]: { a } = {} } = obj; console.log(a);
Take a look at the following three cases, where I've used optional chaining .
You need to first check if the first element of the array ( index 0 ) exists and then check if there's a field a
in it.
// Case 1: const obj1 = [{ a: "a" }]; console.log(obj1?.[0]?.a); // "a" // Case 2: const obj2 = [{ b: "b" }]; console.log(obj2?.[0]?.a); // undefined // Case 3: const obj3 = []; console.log(obj3?.[0]?.a); // undefined
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.