Forum Moderators: open

Message Too Old, No Replies

Checking if values of an object are empty

         

csdude55

7:51 pm on Jul 30, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have an object that is set using:

// uses jQuery to get form values
setObj = {
username : $('#username').val(),
price : $('input[name=price]').val(),
subject : $('input[name=subject]').val() || $('input[name=ad_title]').val(),
comment : $('#comment').html() || $('#commentText').val()
};


Later, I check to see if there's data in the object before proceeding. I was using:

if (Object.values(setObj).length > 0) { ... }


but discovered that it ALWAYS succeeds because blank values still count! So the entire form could be empty, but it would still return 4 instead of the expected 0.

Then I was going to use this:

if (setObj.price + setObj.subject + setObj.comment === '') { ... }


but quickly discovered that these could equal "undefinedundefinedundefined", "NaN", or "".

Is there a better way to see if all fields are empty than this?

if (
// this line can become a real issue if I add more keys later and forget to modify it
setObj.price + setObj.subject + setObj.comment === 'undefinedundefinedundefined' ||

setObj.price + setObj.subject + setObj.comment === 'NaN' ||
setObj.price + setObj.subject + setObj.comment === ''
) { ... }

phranque

9:44 pm on Jul 30, 2022 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



i would try evaluating the object's key values only if the relevant form values are "non-blank".

this line can become a real issue if I add more keys later and forget to modify it

alternatively, you could loop on the values to calculate the total length of the object's values:
for (let value of Object.values(setObj)) {
...
}

Fotiman

1:07 am on Jul 31, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I would suggest using `Object.values` to get the array, and then use `.every` to verify that none of them are empty.

if (Object.values(setObj).every(isNotEmpty)) {


function isNotEmpty(value) {
return value !== undefined && value !== null && value.trim();
}

csdude55

7:42 pm on Jul 31, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I combined the two, this seems to be working well :-) I opted to modify the values in the object since I'll use something similar later, and it's better to permanently change them to ''.

I had to play with the return value, though; if the sent value was "" then I got an error that trim wasn't a function, and just returning true or false would save the value as "false" (which ended up being no better than "undefined").

for (var x in setObj) { setObj[x] = isNotEmpty(setObj[x]); }

if (setObj.price + setObj.subject + setObj.comment === '') { ... }

function isNotEmpty(v) {
return (v === undefined || v === null) ?
'' :
v.toString().trim();
}