LoginSignup
0
0

More than 1 year has passed since last update.

【TypeScript】多次元オブジェクトの1次元化

Last updated at Posted at 2022-10-02

やりたいこと

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

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

こんな感じに変換したい

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

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

TypeScriptのコード

JavaScriptなら単に型情報を省けばOK

type Input = { [x: string]: string | Input };
type Output = Record<string, string>;

/** 多次元オブジェクトの1次元化 */
function flattenObject(obj: Input, sep: string): Output {
  const entries = Object.entries(obj)
    .map(([k1, v1]) => {
      if (typeof v1 === 'string') {
        return [[k1, v1]];
      } else {
        const childObj = flattenObject(v1, sep);
        return Object.entries(childObj).map(([k2, v2]) => [k1 + sep + k2, v2]);
      }
    })
    .flat();
  return Object.fromEntries(entries) as Output;
}

// こんな感じで使う
flattenObject(hoge, '-')
0
0
2

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