How can I do object destructuring with condition?

Viewed 7229

So I have:

// some function that returns two arrays ..
getArrays() {
  return {
    arr1: [...],
    arr2: [...]
  };
}

// and then ..
let arr1 = [];
let arr2 = [];
if (someCondition) {
  { arr1, arr2 } = getArrays();
}

// here we expect arrays, even if they are empty ..

Of course, this throws an error. Is this even possible?

PS: I can use default values and directly call the function, but still - I think it should be possible.

1 Answers

One solution is to wrap the destructuring expression with parentheses:

// some function that returns two arrays ..
function getArrays() {
  return {
    arr1: [1],
    arr2: [2]
  };
}
const someCondition = true;
let arr1 = [];
let arr2 = [];

if (someCondition) {
  ({ arr1, arr2 } = getArrays());
}

console.log(arr1, arr2);

Another solution is to move the condition to the getArrays() function, and if the condition is false return two empty arrays:

const getArrays = (condition) =>
  condition ? 
    { arr1: [1], arr2: [2] }
    :
    { arr1: [], arr2: [] };

const someCondition = true;
const { arr1, arr2 } = getArrays(someCondition);

console.log(arr1, arr2);

You can also use the condition and ternary outside of the function:

const getArrays = () => ({ arr1: [1], arr2: [2] });

const someCondition = true;
const { arr1, arr2 } = someCondition ? getArrays() : { arr1: [], arr2: [] };

console.log(arr1, arr2);

Related