Skip to content
Advertisement

Sorting an Objects keys/values by an array of objects the object is created from

So im generating a form for users of my application to fill out from an array of objects, each object has its own validation data….etc. This issue is when the user fills out the form and a new object is created from it to send to the back end, if the user fills out the form in order, the object is in the proper order, but if the user goes back and changes a value, the object is put out of order.
Original Object:

JavaScript

The new Object is built with a handle change method
Object Handle:

JavaScript

Correct Object:

JavaScript

Incorrect Object:

JavaScript

I’m having a hard time trying to figure out a way of comparing the new form against the formData to make sure they stay in the proper order. If anyone could give some advice and help me out I’d appreciate it.

Advertisement

Answer

You are going to have a problem with your state, you may not be getting the previous state or newForm because of useState‘s asynchronous behavior. You are going to want to use an arrow function with a parameter for your previous state to get the previous state. Like this:

JavaScript

Also here is some code from my github repo for comparing objects

JavaScript

Hopefully this helps.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement