javascript - Best way to remove empty keys from a FormData object? - Stack Overflow

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

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.

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.

Share Improve this question asked Jan 19, 2022 at 20:03 GemGem 1111 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

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

This is how i do it

let data = Array
   .from(new FormData(document.querySelector('#form')))
   .filter(function([k, v]) { return v }); //this will return an array to make it an object use;
let formData = Object.formEntries(data) //this will return an object with key and value (make sure in your inputs you have the name attribute)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744506795a4577750.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信