I have an object like this
const obj = [{a: 'a'}];
I can get it like:
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 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)
|| {} there's no need for optional chaining o.Oobj being undefined, OR operator is concerned what will be returned with obj[1] if obj[1] is undefined.obj exists but obj.x may not. There's no need for optional chaining.const a = obj?.[1]?.a, do I still need a fallback?obj doesn't existYou 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);
? like const a = obj?.[1]?.aTake 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
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.
const a = obj?.[1]?.a
obj?.[1]returns just asundefinedasobj[1]would), you should either drop the destructuring and use a simple property access (with?.where needed) or use destructuring everywhere with default values.const a = obj?.[1]?.a