LoginSignup
3
0

More than 3 years have passed since last update.

オブジェクトのある特定のキーを取得する方法

Last updated at Posted at 2020-10-19

オブジェクトのある特定のキーを取得する方法が日本語であまり見当たらなかったのでまとめてみました。

ユーザーの情報が格納されているusersオブジェクトがあるとする。

const users = {
  "Jonh": {
    sex: 'male',
    age: 30,
    height: 175,
  },
  "Bob": {
    sex: 'male',
    age: 25,
    height: 175,
  },
  "Hanna": {
    sex: 'female',
    age: 23,
    height: 160,
  },
};

全てのキーの取得方法

オブジェクトの中にあるキーを全て取得したい場合には、

Object.keys(users); // return Jonh, Bob, Hanna

Object.keys()メソッドの引数に、オブジェクト変数を入れてあげることで取得できる。

ある特定のキーの取得方法

Object.keys(users)[0]; // return Jonh

[]の中に取得したいオブジェクトのキー番号を指定することで取得ができる。
一番初めのキーを取得したい場合には、0を指定。

これでok

参考サイト

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0