LoginSignup
4
3

More than 5 years have passed since last update.

JavaScript で Object を flatten する

Last updated at Posted at 2017-12-18

Object が key => array となっているような Object を flatten する場合。(他の場合も少し頑張ればいけます)

下記は TypeScript ですが、JSも似たような感じでできます。

  static flatten(object: object): string[][] {
    const flattenSub = (sum: string[], obj: any): string[][] => {
      if (obj instanceof Array) {
        return (obj as string[]).map( val => {
          return sum.concat(val);
        });
      } else if (obj instanceof Object ) {
        return Object.keys(obj).reduce( (result, key): string[][] => {
          flattenSub(sum.concat(key), obj[key]).forEach(arr => {
            result.push(arr);
          });
          return result;
        }, []);
      }
    };
    return flattenSub([], object);
  }
4
3
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
4
3