Skip to main content
Back to problems
#2705
Medium JavaScript

Compact object

67.7% acceptance
Mar 2, 2026
227
25
Given an object or array obj, return a compact object. A compact object is the same as the original object, except with keys containing falsy values removed. This operation applies to the object and any nested objects. Arrays are considered objects where the indices are keys. A value is considered falsy when Boolean(value) returns false. You may assume the obj is the output of JSON.parse. In other words, it is valid JSON.

Solution

TypeScript
Time O(n)
Space O(1)
LeetCode
solution.ts
type JSONValue =
  | null
  | boolean
  | number
  | string
  | JSONValue[]
  | { [key: string]: JSONValue };
type Obj = Record<string, JSONValue> | Array<JSONValue>;

function compactObject(obj: Obj): Obj {
  if (Array.isArray(obj)) {
  return (obj as JSONValue[])
    .filter(Boolean)
    .map((item) =>
    typeof item === "object" && item !== null
      ? compactObject(item as Obj)
      : item,
    ) as JSONValue[];
  }
  const result: Record<string, JSONValue> = {};
  for (const key of Object.keys(obj as Record<string, JSONValue>)) {
  const val = (obj as Record<string, JSONValue>)[key];
  if (val) {
    result[key] =
    typeof val === "object" && val !== null
      ? (compactObject(val as Obj) as JSONValue)
      : val;
  }
  }
  return result;
}