如何使用字符串键名解构对象属性

问题描述 投票:0回答:3

如何解构这个对象:

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

所以我可以获得(“Oath In Felghana”)变量中releases对象的第一个键名。 我试过了,但没用

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

PS:我想拿到钥匙名字(Oath In Felghana)

不是值 ["USA", "Japan"]

javascript destructuring object-destructuring
3个回答
2
投票

可以通过如下方式获取键名:

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

2
投票

从上面的评论...

const [ game ] = Object.keys(game.releases);
——彼得塞利格

[我]还有其他方法吗?因为我想在单个解构赋值中解构所有对象属性。 – B-M Amine

如果OP想要将

game.releases
的所有游戏名称相关条目与不相关的
Origin
属性分开,OP需要利用object destructuringrest 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; }


0
投票

https://jsfiddle.net/c0ne2Lrv/8/

你会在这里找到答案

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

({
  title: t,
  developer: d,
  releases:  {
    "Oath In Felghana":[u,j],
    "Ark Of Napishtim":{US:u_price, JAP:j_price},
    Origin:or
  }
} = game);

[o,a,] = Object.keys(game.releases);




// Write Your Destructuring Assignment/s Here

console.log(`My Favourite Games Style Is ${t} Style`);
// My Favourite Games Style Is YS Style

console.log(`And I Love ${d} Games`);
// And I Love Falcom Games

console.log(`My Best Release Is ${o} It Released in ${u} and ${j}`);
// My Best Release Is Oath In Felghana It Released in USA & Japan

console.log(`Although I Love ${a}`);
// Although I Love Ark Of Napishtim

console.log(`${a} Price in USA Is ${u_price}`);
// Ark Of Napishtim Price in USA Is 20 USD

console.log(`${a} Price in Japan Is ${j_price}`);
// Ark Of Napishtim Price in Japan Is 10 USD

console.log(`Origin Price Is ${or}`);
// Origin Price Is 30 USD
© www.soinside.com 2019 - 2024. All rights reserved.