简体   繁体   中英

How to destructure object properties with string key name

How to destructure this object:

 const game = { title: "YS", developer: "Falcom", releases: { "Oath In Felghana": ["USA", "Japan"], "Ark Of Napishtim": { US: "20 USD", JAP: "10 USD", }, Origin: "30 USD", }, };

so I can get ( "Oath In Felghana" )the first key name of releases object in a variable. I tried this but it didn't work

 const{Object.keys(game.releases)[0]:keyName} = game

PS: I want to get the key Name (Oath In Felghana)

not the value ["USA", "Japan"]

You can get the key name as follows:

const [ keyName ] = Object.keys(game.releases);

From the above comments...

const [ game ] = Object.keys(game.releases); – Peter Seliger

[I]s there any other way to do it? because I want to destructure all object properties in a single destructuring Assignment. – BM Amine

In case the OP wants to separate all game name related entries of game.releases from the non related Origin property, the OP needs to utilize the object destructuring rest property

 const game = { title: "YS", developer: "Falcom", releases: { "Oath In Felghana": ["USA", "Japan"], "Ark Of Napishtim": { US: "20 USD", JAP: "10 USD", }, Origin: "30 USD", }, }; const [ firstGameName ] = Object.keys(game.releases); console.log({ firstGameName }); // OP... [I]s there any other way to do it? // because I want to destructure all // object properties in a single // destructuring Assignment. const allGameNames = Object.keys( // rest property as of object destructuring... //... see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#rest_property] (({ Origin, ...releaseEntries }) => releaseEntries)(game.releases) ); console.log({ allGameNames });
 .as-console-wrapper { min-height: 100%;important: top; 0; }

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