|
| 1 | +// Question Link: https://leetcode.com/problems/compact-object/description/?envType=study-plan-v2&envId=30-days-of-javascript |
| 2 | +// Solution Link: https://leetcode.com/problems/compact-object/solutions/5458268/easy-javascript-solution/ |
| 3 | + |
| 4 | +/* |
| 5 | +2705. Compact Object |
| 6 | +
|
| 7 | +Given an object or array obj, return a compact object. |
| 8 | +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. |
| 9 | +You may assume the obj is the output of JSON.parse. In other words, it is valid JSON. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +Input: obj = [null, 0, false, 1] |
| 13 | +Output: [1] |
| 14 | +Explanation: All falsy values have been removed from the array. |
| 15 | +
|
| 16 | +Example 2: |
| 17 | +Input: obj = {"a": null, "b": [false, 1]} |
| 18 | +Output: {"b": [1]} |
| 19 | +Explanation: obj["a"] and obj["b"][0] had falsy values and were removed. |
| 20 | +
|
| 21 | +Example 3: |
| 22 | +Input: obj = [null, 0, 5, [0], [false, 16]] |
| 23 | +Output: [5, [], [16]] |
| 24 | +Explanation: obj[0], obj[1], obj[3][0], and obj[4][0] were falsy and removed. |
| 25 | + |
| 26 | +Constraints: |
| 27 | +obj is a valid JSON object |
| 28 | +2 <= JSON.stringify(obj).length <= 10^6 |
| 29 | +*/ |
| 30 | + |
| 31 | + |
| 32 | + |
| 33 | +/** |
| 34 | + * @param {Object|Array} obj |
| 35 | + * @return {Object|Array} |
| 36 | + */ |
| 37 | + |
| 38 | +var compactObject = function(obj) { |
| 39 | + if (obj === null) |
| 40 | + return null; |
| 41 | + |
| 42 | + if (Array.isArray(obj)) |
| 43 | + return obj.filter(Boolean).map(compactObject); |
| 44 | + |
| 45 | + if (typeof obj !== "object") |
| 46 | + return obj; |
| 47 | + |
| 48 | + const compacted = {}; |
| 49 | + |
| 50 | + for (const key in obj) { |
| 51 | + let value = compactObject(obj[key]); |
| 52 | + |
| 53 | + if (Boolean(value)) |
| 54 | + compacted[key] = value; |
| 55 | + } |
| 56 | + |
| 57 | + return compacted; |
| 58 | +}; |
0 commit comments