DEV Community

Discussion on: Destructuring JavaScript objects like a pro

Collapse
n1ru4l profile image
Laurin Quast

You can even do this wizardry:

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

const  propName = "prop1";

// destructure dynamic property
const { [propName]: value } = object;

value === "value1" // true
Collapse
willamesoares profile image
Will Soares Author

Yes! Dynamic destructuring!
allthethings

Collapse
vitorreisdev profile image
Vitor Reis

js wizardry... That's pretty cool I haven't thought of that

Collapse
itspauloroberto profile image
Paulo Roberto Rosa

It is possible to do it nested???

Collapse
n1ru4l profile image
Laurin Quast

You mean the following?

const object = { prop1: "value1", prop2: { a: "abc" } };
const  propName1 = "prop2";
const propName2 = "a";
const { [propName1]: { [propName2]: value } } = object;
value === "abc" // true