Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

345
Visualizações
Best way to remove empty keys from a FormData object?

I'm constructing an Ajax request using FormData and I can't find an accepted way to eliminate empty keys.

I wrote my own way to do it but I'm wondering, is there a way to do it with no iterator, or a more efficient way to iterate it?

let payload = new FormData(document.querySelector('#form'));
[...payload.entries()].forEach(([key, value]) => {
    if (value == 0) payload.delete(key);
});

I expect a lot of calls to this particular function so every bit of optimization helps.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You won't be able to avoid an iterator if you want to filter the entire FormData object because FormData will always return an object with key/value pairs.

If you can use the recent JS for things (or at least relatively recent stuff), the simplest/readable version is probably going to use Array.filter(). Something like the following.

let data = Array
   .from(new FormData(document.querySelector('#form')))
   .filter(function([k, v]) { return v });

Array.from() is used to coerce the object into an Array prototype so you can use filter() on it. But you could just as easily use your current Array coercion on it.

One nice thing about using Filter, instead of current one is that Filter will return a new Array with the cleaned up data, rather than mutating the current payload like you are currently doing.

MDN Reference Links

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda