Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  98] [ 6]  / answers: 1 / hits: 5328  / 5 Years ago, tue, august 27, 2019, 12:00:00

I'm sending some data to my backend and I only want to add key/value pairs to my form data when they contain values.



Currently I'm conditionally added the values if they have a length greater than zero.



const personDetails = this.personDetails;
let formData = {}

if (personDetails.email.length) {
formData.email = personDetails.email;
}
if (personDetails.phone.length) {
formData.phone = personDetails.phone;
}

axios.put(url, formData).then(() => blah);


Is there a less verbose way of doing this?


More From » javascript

 Answers
2

If you have lots of fields to do this with, you can use a loop so you don't have to repeat the if statements.



[email, phone, ...].forEach(field => {
if (personDetails[field].length) {
formData[field] = personDetails[field];
}
});

[#6451] Thursday, August 22, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxinec

Total Points: 117
Total Questions: 116
Total Answers: 116

Location: Bangladesh
Member since Sat, Jan 23, 2021
3 Years ago
maxinec questions
;