How to perform Array deconstruct and then retrieve deconstructed object's value at the same time in JavaScript?

Viewed 44

Please see this minimum example

const [one, two, three] = [
  { name: "Joseph" },
  { name: "Amy" },
  { name: "Jim" }
];

I can array deconstruct first level, how can I do it with second level like this:

const [oneName: one.name, twoName: two.name, threeName: three.name] = [
  { name: "Joseph" },
  { name: "Amy" },
  { name: "Jim" }
];

It's pseudocode, the syntax is wrong, but you get the idea.

Is it possible to do this in JavaScript?

1 Answers

It's a bit similar to as if you were declaring an array of objects, only with a const in front of it. Instead of putting the values on the right-hand side of a :, put the new variable name to put the string there into:

const [{name: oneName}, {name: twoName}, {name: threeName}] = [
  { name: "Joseph" },
  { name: "Amy" },
  { name: "Jim" }
];

console.log(oneName);
console.log(twoName);
console.log(threeName);

But while this is possible to do, it's weird and (IMO) pretty unreadable. I wouldn't recommend it.

Related