Clear objects with empty subobjects

-3

Hello. Today I had a question. How can I efficiently create a function that allows me to clean a specific object? For example:

const obj = {
   chave1: 'conteudo',
   chave2: {},
   chave3: '',
   chave4: {
    chave1: 'conteudo1',
    chave2: {}
    chave3: {
       chave1: [],
       chave2: {},
       chave3 'conteudo2'
    }
   }
}

As output would have to exit the following:

{
  chave1: 'conteudo',
  chave4: {
   chave1: 'conteudo1',
   chave3: {
    chave3: 'conteudo2',
   }
  }
}

How can I solve the problem without compromising performance?

    
asked by anonymous 13.08.2018 / 18:26

1 answer

5

Just scan the properties of the object and use delete in those that are empty, doing so recursively. See below the limpar function that does this:

const obj = {
    chave1: 'conteudo',
    chave2: {},
    chave3: '',
    chave4: {
        chave1: 'conteudo1',
        chave2: {},
        chave3: {
            chave1: [],
            chave2: {},
            chave3: 'conteudo2'
        }
    }
};

function limpar(obj) {
    var vazio = true;
    for (var e in obj) {
        var k = obj[e];
        if (!k || ((k instanceof Object || k instanceof Array) && limpar(k))) {
            delete obj[e];
        } else {
            vazio = false;
        }
    }
    return vazio;
}

limpar(obj);
console.log(obj);
    
13.08.2018 / 18:44