Skip to content

2705. Compact Object 👍

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };
type Obj = Record<string, JSONValue> | Array<JSONValue>;

function compactObject(obj: Obj): Obj {
  return dfs(obj) as Obj;
}

function dfs(value: JSONValue): JSONValue {
  if (value === null) {
    return null;
  }
  if (Array.isArray(value)) {
    return value.filter(Boolean).map(dfs);
  }
  if (typeof value === 'object') {
    for (const key of Object.keys(value)) {
      if (Boolean(value[key])) {
        value[key] = dfs(value[key]);
      } else {
        delete value[key];
      }
    }
  }
  return value;
}