0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TypeScript】多次元オブジェクトの末端の値を簡単に取り出したい

Last updated at Posted at 2022-10-02

やりたいこと

こんなオブジェクトがあったら

const hoge = {
  aaa: 'A',
  bbb: {
    ccc: 'BC',
    ddd: {
      eee: 'BDE',
      fff: 'BDF',
    },
  },
};

こんな感じで取り出したい

pick(hoge, 'aaa') // 'A'
pick(hoge, 'bbb-ccc') // 'BC'
pick(hoge, 'bbb-ddd-eee') // 'BDE'

TypeScriptで動的に取り出す部分を変えたい場合、hoge[key1][key2]のように取り出すと型エラーが出るため。

TypeScriptのコード

単純化のためにキーもバリューもstring型とする。

--- 2022/10/03更新 ---
@shiracamusさん @akebi_mhさん のアドバイスを受けてコード更新。
JavaScriptの場合の書き方はお二方のコメントをご参照ください。

type Input = { [x: string]: string | Input };

function pick(obj: Input, key: string) {
  return key
    .split('/')
    .reduce<string | Input>(
      (o, c) => (typeof o === 'object' ? o[c] ?? '' : o),
      obj,
    );
}
0
0
4

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?