Destroy object properties in array values

Is there a way to destroy an object and assign its properties to an array, and not as variables? For instance:

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

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

This works, but this requires rearranging the variables as array values.

I tried:

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

but this is a syntax error.

I had a similar idea with Object.valuesas in

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

... but this has the same problem as the inability to perform destructuring in expressions.

+4
source share
4 answers

Indeed, the answer you want is to go back in time and use the operatorwith before it is (fairly) declared evil

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

, . , , - . :

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

:

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

, . , , , . , !

+1

. .

Object.values, (.. 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);

, . .

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

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

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

, ?

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

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

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

You can describe an object in this way

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

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

Remember that the keys of an object are not alphabetic, so it might be better to create a function that returns 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 behavior.

-1
source

Source: https://habr.com/ru/post/1693423/


All Articles