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.
var compactObject = function(obj) {
};
Example 1:
Input: obj = [null, 0, false, 1]
Output: [1]
Example 2:
Input: obj = {"a": null, "b": [false, 1]}
Output: {"b": [1]}
Example 3:
Input: obj = [null, 0, 5, [0], [false, 16]]
Output: [5, [], [16]]
調用了遞迴,但速度很慢
var compactObject = function(obj) {
const result = Array.isArray(obj) ? [] : {};
for (let key in obj) {
let val = obj[key];
if (val) {
if (typeof val === 'object') {
val = compactObject(val);
}
Array.isArray(obj) ? result.push(val) : result[key] = val;
}
}
return result;
};
//Runtime 96ms
//Beats 27.49%of users with JavaScript
//Memory 58.03MB
//Beats 12.53%of users with JavaScript