🔗LC2705 🟡 Medium 🧩 Pattern – JSON, Arrays and Objects
📅 Day 27/30 Days of JavaScript
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
Input: obj = [null, 0, false, 1]
Output: [1]
Explanation: All falsy values have been removed from the array.
Input: obj = {"a": null, "b": [false, 1]}
Output: {"b": [1]}
Explanation: obj["a"] and obj["b"][0] had falsy values and were removed.Code language: JavaScript (javascript)Solution
/**
* @param {Object|Array} obj
* @return {Object|Array}
*/
var compactObject = function (obj) {
// Return early if obj not an object or null
// null check because null is of type object
if (typeof obj !== 'object' || obj === null) {
return obj;
}
// If obj is an array, filter out falsy values and recursively compact each element
// Boolean is an inbulit js function that returns true or false for given value
if (Array.isArray(obj)) {
return obj.filter(Boolean).map(compactObject);
}
// If obj is an object check for truthyness of each value for the key
// Recursively compact each value of obj, if value contains any nested values they are filtered
const result = {};
for (const key in obj) {
const value = compactObject(obj[key]);
if (value) {
result[key] = value;
}
}
return result;
};Code language: JavaScript (javascript)