mani deepak
mani deepak

Reputation: 411

Can I declare all keys of an object as variables?

I wanted to similar thing like

let { * } = {test1: 'test', test2: 'test2'};

The above code should declare two new variables test1 and test2.

Edit1: My concern here is the right side object may have 10 keys. I don't want to do

let { key1, key2 , key3 , ..., key10 } =

Instead, is there any way of getting all the 10 keys?

Upvotes: 3

Views: 886

Answers (2)

solanki...
solanki...

Reputation: 5098

Destructuring objects in ES6: Destructuring on objects lets you bind variables to different properties of an object. There is a helpful syntactical shortcut for when the property and variable names are the same.

let { test1, test2 } = {test1: 'test', test2: 'test2'};
console.log(test1, test2);

Below a simple two properties object example for destructuring the properties dynamically.

const obj = { prop1: "value1", prop2: "value2" };

const  propName1 = "prop1";
const  propName2 = "prop2";

// destructure dynamic property
const { [propName1]: val1, [propName2]: val2 } = obj;
console.log('destructure dynamic property values : ', val1, val2);

Upvotes: 3

ZER0
ZER0

Reputation: 25322

There is no currently syntax for something like that: you have to be explicit. Even for importsyntax doesn't exists something like that, that would import all the "keys" (exported value) in the scope without being explicit (declaring which "keys" import, or assign the whole module to an object).

If you need most of the keys of an object, probably the best way it would be just use the object directly (o.test1) without destructuring.

Of course in case you have access to the current scope object, such as globalThis, you can always doing something like:

Object.entries(o).forEach(([key, value]) => globalThis[key] = value)

But first, it will work only if you're assign the object value to the global object (so no local scope); and second I don't see how it's different writing this code and then using test1 instead of avoid such code and write o.test1. (And, of course it's something really horrible to write that you shouldn't never do it, I added just for completition).

Upvotes: 4

Related Questions