Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparing javascript FormData object

How do I compare FormData object, I am trying to check if the form has been changed or not before sending the ajax request.

But it seems objects cannot be compared. Is there any way to convert it to js Object or an elegant way?

let a = new FormData()
let b = new FormData()

console.log(a === b ) // returns false
like image 963
rho Avatar asked Nov 01 '25 09:11

rho


1 Answers

I would try this

const a = new FormData();

a.append("username", "Alexander");
a.append("accountnum", 123);

const b = new FormData();

b.append("username", "Alexander");
b.append("accountnum", 123);

let different = false
for (let [key, value] of b.entries()) {
  if (a.get(key) !== value) different = true
}

Or you could try iterating over both objects at the and comparing them, that might be more performant.

JSON.stringify([...a.entries()]) === JSON.stringify([...b.entries()])
like image 184
alexandercannon Avatar answered Nov 03 '25 22:11

alexandercannon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!