Clear objects with empty subobjects

Asked

Viewed 246 times

-3

Hello. Today I have 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 come out the following:

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

How can I solve the problem without compromising performance?

  • It depends on the version you are using.. es2015 ? es2016 ? native ?

  • "How can I solve the problem without compromising performance?" I don’t care about summers but about performance. What is the best way to iterate objects? Regardless of versions.

  • 2

    "Without compromising performance" - this will depend on the object. You have to iterate over the whole object to remove the empty values, there is no other way. It costs processing time. If the object is small, it should not have much impact on performance. If it is large, it may have more impact.

1 answer

5


Just scan the properties of the object and use delete on those that are empty, doing so recursively. See below the function limpar 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.