How to Deeply Remove Null Values, Empty Objects and Empty Array from an Object

How to deeply remove null values, empty objects and empty array from an object

Here is a function that clean the object recursively. It will loop deeply through all the properties and remove null values, null arrays and null objects:

cleanUpObject(jsonObject: object): object {

Object.keys(jsonObject).forEach(function (key, index) {
const currentObj = jsonObject[key]

if (_.isNull(currentObj)) {
delete jsonObject[key]
} else if (_.isObject(currentObj)) {
if (_.isArray(currentObj)) {
if (!currentObj.length) {
delete jsonObject[key]
} else {
const cleanupArrayObj = []
for (const obj of currentObj) {
if (!_.isNull(obj)) {
const cleanObj = this.cleanUpJson(obj)
if (!_.isEmpty(cleanObj)) {
cleanupArrayObj.push(cleanObj)
}
}
}
if (!cleanupArrayObj.length) {
delete jsonObject[key]
} else {
jsonObject[key] = cleanupArrayObj
}
}
} else {
if (_.isEmpty(Object.keys(jsonObject[key]))) {
delete jsonObject[key]
} else {
jsonObject[key] = this.cleanUpJson(currentObj)

if (_.isEmpty(Object.keys(jsonObject[key]))) {
delete jsonObject[key]
}
}
}
}
}, this)

return jsonObject
}

How to deep remove falsey values and empty objects from an object using lodash

var test = {
a: undefined,
b: 2,
c: 4,
d: undefined,
e: {
f: {},
g: null
}
};

function clean(obj) {
for (var propName in obj) {
if (_.isObject(obj[propName])) {
clean(obj[propName]);
}
if (obj[propName] === null || obj[propName] === undefined || _.isObject(obj[propName]) && _.isEmpty(obj[propName])) {
delete obj[propName];
}
}
}

clean(test);
console.log(test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

Remove empty objects from an object using recursion (using vanila ES6 javascript)

It's an interesting problem. I think it can be solved elegantly if we write a generic map and filter function that works on both Arrays and Objects -

function map (t, f)
{ switch (t?.constructor)
{ case Array:
return t.map(f)
case Object:
return Object.fromEntries(Object.entries(t).map(([k, v]) => [k, f(v, k)]))
default:
return t
}
}

function filter (t, f)
{ switch (t?.constructor)
{ case Array:
return t.filter(f)
case Object:
return Object.fromEntries(Object.entries(t).filter(([k, v]) => f(v, k)))
default:
return t
}
}

We can write your removeEmpties program easily now -

const empty =
Symbol("empty") // <- sentinel

function removeEmpties (t)
{ switch (t?.constructor)
{ case Array:
case Object:
return filter(map(t, removeEmpties), nonEmpty)
default:
return nonEmpty(t) ? t : empty // <-
}
}

Now we have to define what it means to be nonEmpty -

function nonEmpty (t)
{ switch (t?.constructor)
{ case Array:
return t.length > 0
case Object:
return Object.keys(t).length > 0
default:
return t !== empty // <- all other t are OK, except for sentinel
}
}

Finally we can compute the result of your input -

const input =
{a: {b: 1, c: {a: 1, d: {}, e: {f: {}}}}, b: {}}

console.log(removeEmpties(input))

Expand the snippet below to verify the result in your browser -

const empty =
Symbol("empty")

function removeEmpties (t)
{ switch (t?.constructor)
{ case Array:
case Object:
return filter(map(t, removeEmpties), nonEmpty)
default:
return nonEmpty(t) ? t : empty
}
}

function nonEmpty (t)
{ switch (t?.constructor)
{ case Array:
return t.length > 0
case Object:
return Object.keys(t).length > 0
//case String: // <- define any empty types you want
// return t.length > 0
default:
return t !== empty // <- all other t are OK, except for sentinel
}
}

function map (t, f)
{ switch (t?.constructor)
{ case Array:
return t.map(f)
case Object:
return Object.fromEntries(Object.entries(t).map(([k, v]) => [k, f(v, k)]))
default:
return t
}
}

function filter (t, f)
{ switch (t?.constructor)
{ case Array:
return t.filter(f)
case Object:
return Object.fromEntries(Object.entries(t).filter(([k, v]) => f(v, k)))
default:
return t
}
}

const input =
{a: {b: 1, c: {a: 1, d: {}, e: {f: {}}}}, b: {}}

console.log(removeEmpties(input))

How to remove any empty objects from array of nested objects

You could use create a recursive function with reduce and a for...in loop and make it so that both empty objects in a array and as a object value are removed.

const data = [{"name":"South America","locations":[{"name":"Argentina","locations":[{"name":"Buenos Aires","foo":{}},{}]}]},{"name":"Europe","locations":[{"name":"Spain","locations":[{}]}]},{"name":"Asia","locations":[{}]}]

function removeEmpty(data) {
return data.reduce((r, e) => {
if (Object.keys(e).length) {
const obj = {}

for (let k in e) {
if (Array.isArray(e[k])) {
obj[k] = removeEmpty(e[k])
} else if (typeof e[k] === 'object') {
if (Object.keys(e[k]).length) {
obj[k] = removeEmpty(e[k])
}
} else {
obj[k] = e[k]
}
}

r.push(obj)
}

return r;
}, [])
}

console.log(removeEmpty(data))

Remove empty Objects from Array

// Code goes here
myArray = [{ id: "28b", text: "Phill" }, { id: "12c", text: "Peter" }, { id: "43f", text: "Ashley" }, { id: "43f", text: "Ashley" }, { id: "", text: "" }, { id: "9a", text: "James" }, { id: "", text: "" }, { id: "28b", text: "Phill" }
]
var result = _.filter(_.uniq(myArray, function(item, key, a) { return item.id;}), function(element) { return element.id && element.text});console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Javascript removing null or undefined object from array of objects

let arr = [
{
"addrSeq": "12",
"addinfo": [
{
"virAddrSeq": "45"
}
]
},
null
];
arr = arr.filter((i)=>i !== null && typeof i !== 'undefined');
console.log(arr);

How to remove nested empty objects in JavaScript?

instead of checking for null ( obj[k] != null ) , check for Object.values().length ( or Object.keys().length) :