Suppose I have the following:
const myFunction = ({ returnProp = null }) => ({
propA: 'val1',
propB: 'val2',
propC: 'val3'
})[returnProp || {}]
// ^^
// not sure what to put here
If returnProp is null, how can I return the whole object?
If I specify returnProp, I would like it returned:
const propA = myFunction({ returnProp: 'propA' }) // 'val1'
If I do not specify it, I'd like the whole object:
const obj = myFunction({})
/*
{
propA: 'val1',
propB: 'val2',
propC: 'val3'
}
*/
You can achieve it using nullish coalescing operator.
const myFunction = ({ returnProp = null }) => {
const obj = {
propA: "val1",
propB: "val2",
propC: "val3",
};
return obj[returnProp] ?? obj;
};
console.log(myFunction({ returnProp: "propA" }));
console.log(myFunction({ returnProp: null }));
console.log(myFunction({ returnProp: undefined }));
console.log(myFunction({}));
Could maybe use a getter invoked with an empty string:
const myFunction = ({ returnProp = '' }) => ({
propA: 'val1',
propB: 'val2',
propC: 'val3',
get ['']() {delete this['']; return this}
})[returnProp]
console.log(myFunction({ returnProp: "propA" }));
console.log(myFunction({}));