Algorithm
30 Days of JavaScript
Compact Object

2705. Compact Object

Tags

  • JSON

Link

https://leetcode.com/problems/compact-object/description/?envType=study-plan-v2&envId=30-days-of-javascript (opens in a new tab)

Question

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.

Example 1:
Input: obj = [null, 0, false, 1]
Output: [1]
Explanation: All falsy values have been removed from the array.
Example 2:
Input: obj = {"a": null, "b": [false, 1]}
Output: {"b": [1]}
Explanation: obj["a"] and obj["b"][0] had falsy values and were removed.
Example 3:
Input: obj = [null, 0, 5, [0], [false, 16]]
Output: [5, [], [16]]
Explanation: obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed.
Constraints:
  • obj is a valid JSON object
  • 2 <= JSON.stringify(obj).length <= 106

Answer

JavaScript

/**
 * @param {Object} obj
 * @return {Object}
 */
 
var compactObject = function (obj) {
  // Base case: if obj is not an object or is null, return it as is
  if (typeof obj !== "object" || obj === null) {
    return obj;
  }
 
  // Case for arrays: recursively compact each element and remove falsy values
  if (Array.isArray(obj)) {
    const compactArr = [];
    for (let i = 0; i < obj.length; i++) {
      let val = compactObject(obj[i]);
      if (val) {
        compactArr.push(val);
      }
    }
 
    return compactArr;
  }
 
  // Case for objects: create a new compacted object
  const compactObj = {};
 
  for (let key in obj) {
    // Iterate over each key in the object
    const val = compactObject(obj[key]);
    // If the value is truthy, add it to the compacted object
    if (val) {
      compactObj[key] = val;
    }
  }
 
  return compactObj;
};
/**
 * @param {Object|Array} obj
 * @return {Object|Array}
 */
var compactObject = function (obj) {
  function dfs(obj) {
    if (!obj) return false;
    if (typeof obj !== "object") return obj;
    if (Array.isArray(obj)) {
      const res = [];
      for (let i = 0; i < obj.length; i++) {
        const curr = obj[i];
        const subRes = dfs(curr);
 
        if (subRes) {
          res.push(subRes);
        }
      }
      return res;
    }
    const newObj = {};
    for (const key in obj) {
      const subRes = dfs(obj[key]);
      if (subRes) {
        newObj[key] = subRes;
      }
    }
    return newObj;
  }
  return dfs(obj);
};
/**
 * @param {Object|Array} obj
 * @return {Object|Array}
 */
var compactObject = function (obj) {
  if (!obj) {
    return false;
  }
 
  if (typeof obj !== "object") {
    return obj;
  }
 
  if (Array.isArray(obj)) {
    let ans = [];
    for (let i = 0; i < obj.length; i++) {
      const val = compactObject(obj[i]);
      if (val) {
        ans.push(val);
      }
    }
    return ans;
  } else {
    let ans = {};
    for (const key in obj) {
      const val = compactObject(obj[key]);
      if (val) {
        ans[key] = val;
      }
    }
    return ans;
  }
};
/**
 * @param {Object|Array} obj
 * @return {Object|Array}
 */
var compactObject = function (obj) {
  // These three if statements deal with when obj is not an iterable object
  // Steps 1-3 as described above
  if (obj === null) return null;
  if (Array.isArray(obj)) return obj.filter(Boolean).map(compactObject);
  if (typeof obj !== "object") return obj;
 
  // This for loop deals with when obj is an iterable object
  // Steps 4-5 as described above
  const compacted = {};
  for (const key in obj) {
    let value = compactObject(obj[key]);
    if (value) compacted[key] = value;
  }
 
  return compacted;
};