最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I do object destructuring with condition? - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Nov 2, 2018 at 12:15 pesho hristovpesho hristov 2,0602 gold badges27 silver badges50 bronze badges 1
  • Just add parens – Jared Smith Commented Nov 2, 2018 at 12:17
Add a comment  | 

1 Answer 1

Reset to default 19

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

发布评论

评论列表(0)

  1. 暂无评论