Yamila
Yamila

Reputation: 443

How to remove empty objects recursively?

If all the keys of an object is empty, I want to replace them with undefined. For example

{
    a: 1,
    b: {
       c:  2,
       d:  {
           e: undefined,
           f: undefined,
        }
    },
    g:  {
       h: undefined,
       i: undefined,
    }
}

Should be:

{
    a: 1,
    b: {
       c:  2,
       d:  undefined
    },
    g:  undefined
}

It is important to keep the undefined value because it is to remove de key from mongodb

Upvotes: 1

Views: 480

Answers (1)

zangw
zangw

Reputation: 48406

First of all, we can define one function to remove all undefined value to meet your requirement

function removeUndefinedObject(obj) {
    var isAllUndefined = true;

    for (var k in obj) {
        if (typeof obj[k] === 'object') {
            obj[k] = removeUndefinedObject(obj[k]);
        }
        if (typeof obj[k] !== 'undefined')
            isAllUndefined = false;
    }

    if (isAllUndefined)
        obj = undefined;
    return obj;
}

Then to use this function in mongodb collection

var cursor = db.collection.find({}); // get all documents from collection
cursor.forEach(function(doc) {
   // remove undefined value for each document
   removeUndefinedObject(doc); 
   // save this changed doc into this collection
   db.collection.update({_id: doc._id}, doc);
});

Upvotes: 2

Related Questions