javascriptform-data

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

Solution

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