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.
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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With