Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructure object properties into array values

Is there any way to destructure an object and assign its properties into an array rather than as variables? For example:

const obj = { a: 1, b: 2 };

const { a, b } = obj;
const arr = [a, b];

This works, but it requires restating the variables as the array values.

I have tried:

const arr = [(const { a, b } = obj)];

but this is a syntax error.

I had a similar idea with Object.values as in

const arr = Object.values((const { red } = chalk));`

...but this has the same issue of not being able to do destructuring in expressions.

like image 808
Explosion Pills Avatar asked Feb 09 '18 15:02

Explosion Pills


2 Answers

Really the answer you want is to go back in time and use the with statement before it was (rightly) recognized as evil:

var obj = { a: 1, b: 2 };
var arr;
with (obj) {
   arr = [a, b];
}

Any modern answer is going to require more typing than you'd like. A relatively type-safe answer that gets you closer is to use string literals. Stick this in a library:

function arrayDestruct<T, K extends keyof T>(obj:T, ...keys: K[]): T[K][] {
  return keys.map(k => obj[k]);
}

And then use it:

const arr = arrayDestruct(obj, 'a', 'b'); // recognized as number[]

You have to type some quotation marks but it works. It could even be overloaded to produce tuples, but I don't know if you really care enough. Anyway, good luck!

like image 92
jcalz Avatar answered Nov 09 '22 10:11

jcalz


Is there any way to destructure an object and assign its properties into an array rather than as variables?

You can do

const arr = [];
const { a: arr[0], b: arr[1] } = obj;

but I think what you are really looking for is the equivalent to One-liner to take some properties from object in ES 6 which with an array literal would be

const arr = (({a, b}) => [a, b])(obj);
like image 40
Bergi Avatar answered Nov 09 '22 09:11

Bergi