返回介绍

solution / 2700-2799 / 2705.Compact Object / README_EN

发布于 2024-06-17 01:03:01 字数 2945 浏览 0 评论 0 收藏 0

2705. Compact Object

中文文档

Description

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

Solutions

Solution 1

type Obj = Record<any, any>;

function compactObject(obj: Obj): Obj {
  if (Array.isArray(obj)) {
    const temp = [];
    for (const item of obj) {
      if (item) {
        if (typeof item === 'object') temp.push(compactObject(item));
        else temp.push(item);
      }
    }
    return temp;
  }
  for (const [key, value] of Object.entries(obj)) {
    if (!value) delete obj[key];
    else if (typeof value === 'object') obj[key] = compactObject(value);
  }
  return obj;
}
var compactObject = function (obj) {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  if (Array.isArray(obj)) {
    return obj.filter(Boolean).map(compactObject);
  }

  const result = {};
  for (const key in obj) {
    const value = compactObject(obj[key]);
    if (Boolean(value)) {
      result[key] = value;
    }
  }
  return result;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文