Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do object destructuring with condition?

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.

like image 868
pesho hristov Avatar asked Nov 02 '18 12:11

pesho hristov


People also ask

What is correct syntax for object Destructuring?

In this case, the correct syntax is to put the destructuring expression inside parenthesis ( (...) ). Please note that the parenthesis are required when you want to omit the let or const keyword in the destructuring expression itself.

Can we perform Destructuring on nested objects?

Destructuring nested objectsIf we need to access an employee's info we can destructure as many levels as it takes to get to our employee object's properties. const { engineers: { 1: { id, name, occupation, }, }, } = employees; Now we have access to all of the second employee object's properties.

Can you Destructure a function in JavaScript?

Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that's more convenient. Destructuring also works great with complex functions that have a lot of parameters, default values, and so on.


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);
like image 104
Ori Drori Avatar answered Nov 14 '22 22:11

Ori Drori