简体   繁体   English

如何用条件进行对象解构?

[英]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. PS:我可以使用默认值并直接调用该函数,但仍然 - 我认为它应该是可能的。

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: 另一个解决方案是将条件移动到getArrays()函数,如果条件为false返回两个空数组:

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM