The server sends me a data as JSON to descripe a product. A product consists of properties and nested arrays of properties, up to 4 level deep. In the Frontend the user can update deep nested values. Do I need to keep track of the path an then reconstruct the whole JSON object for my updating POST call? Or is there a more elegant way to do it? Or is the design of the backend service bad?
data as JSON
{ "productId": 10, "features": [ { "id": 45, "name": "Customization", "productOptions": [ { "id": 1, "color": ["red", "green"], }, { "id": 2, "slogans": [ {"id": 32, "name":"Thank You"}, {"id": 33, "name":"Thanks a lot"}, ], } ] } ] }
input to edit slogan
<input data-id="32" type="text" name="slogan" />
edit JSON to send back to the server
const update = {"id": 32, "name":"Thank You so much!"} // update slogan array solgansUpdateIndex = slogans.findIndex(obj => obj.id == 32) slogans[solgansUpdateIndex] = update ... // update whole object for the updating POST call {...data, //updateTree}
Advertisement
Answer
You should not need to send the whole object back to the server. What you should do is send a set of ids that uniquely identify which field should be updated.
Example: Let’s take your data where productId is 10 and featureId is 45
You can create a controller in the backend such as updateProductSlogan(int productId, int featureId, int sloganId, String/Slogan newSlogan).
And then what this endpoint should do is get the corresponding slogan from your database with a query, using these ids and update that slogan with value of newSlogan param.
Note: If only field that contains slogans is the features field you can also hardcode that and change the method to updateProductSlogan(int productId, int sloganId, String/Slogan newSlogan).
in which you will fetch the features property with no need to use an id for.