g2701_2800.s2705_compact_object.solution.ts Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
// #Medium #2023_09_14_Time_80_ms_(88.30%)_Space_53.2_MB_(70.41%)
type Obj = Record
function compactObject(obj: Obj): Obj {
if (Array.isArray(obj)) {
let retArr = []
obj.forEach((e, idx) => {
if (e) {
retArr.push(compactObject(e))
}
})
return retArr
} else if (obj !== null && typeof obj === 'object') {
let retObj = {}
for (const key of Object.keys(obj)) {
if (obj[key]) {
retObj[key] = compactObject(obj[key])
}
}
return retObj
}
return obj
}
export { compactObject }