简体   繁体   中英

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

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()])

You can use formData.entries() .

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

let arr1 = [];
let arr2 = [];

for(let pair of a.entries()) {
    const key = pair[0];
    arr1.push({[key]: pair[1]})
}

for(let pair of b.entries()) {
    const key = pair[0];
    arr2.push({[key]: pair[1]})
}

And then you can just compare two arrays of objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM