简体   繁体   中英

Can I do array destructuring assignment inside an object declaration?

I know I can do this:

const [MIN_SPEED, MAX_SPEED] = [0.4, 4.0];

What I want is:

const SpeedManager = {
  [MIN_SPEED, MAX_SPEED]: [0.4, 4.0]
}

which is equivalent for:

const SpeedManager = {
  MIN_SPEED: 0.4,
  MAX_SPEED: 4.0
}

but the syntax was invalid, how can I achieve that?

It's not possible - anything involving destructuring will necessary assign values to references (either a standalone variable name, or a nested property). But here, you don't have a reference, at least not while still inside the object initializer.

I'd stick with the non-destructuring method, though an ugly alternative is:

 const SpeedManager = {}; ([SpeedManager.MIN_SPEED, SpeedManager.MAX_SPEED] = [0.4, 4.0]); console.log(SpeedManager);

As pointed out, it isn't possible, an alternative could be to zip the two arrays and then use Object.fromEntries() to construct the object for you:

 const zip = (arr1, arr2) => arr1.map((e, i) => [e, arr2[i]]); const res = Object.fromEntries( zip(['MIN_SPEED', 'MAX_SPEED'], [0.4, 4.0]) ); console.log(res);

You need a step between for getting values from an array and return an object.

 const convert = ([MIN_SPEED, MAX_SPEED]) => ({ MIN_SPEED, MAX_SPEED }), speedManager = convert([0.4, 4.0]); console.log(speedManager);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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