简体   繁体   中英

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.

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!

You can't achieve that in one hit with destructuring. You have to have one extra line of code.

You can use Object.values , but not without losing type fidelity (ie you end up with an Array<any> .

interface ObjectConstructor {
    values(obj: {}): any[];
}

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

// Array<any>
const arr = Object.values(obj);

// [1, 2]
console.log(arr);

So you have a trade off. One line of code in exchange for correct type information seems like the economic win.

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

// Array<number>
const arr = [a, b];

// [1, 2]
console.log(arr);

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

You can desconstruct the object like this

const [a, b] = Object.values(obj);

console.log(a); // 1
console.log(b); // 2

Remember that the keys of the object is not alphabetical, so its perhaps better to create a function which returns the sorted keys, so that you know that the values are set correctly.

function deconstructObject(obj){
    const arr = [];  
    const keys = Object.keys(obj);
    const sortedKeys = keys.sort();
        for(const key of sortedKeys){
            arr.push(obj[key]);
        }
        return arr;
}

const [a, b] = deconstructObject({b: 2, a: 1 });

console.log(a); // 1
console.log(b); // 2

const newArray = deconstructObject({b: 2, a: 1 });
console.log(newArray); //[1,2]

Now the object will be sorted, so you can predict its behaviour.

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