Search code examples
node.jsreactjsforeachform-data

how can i get without use string to array of object during formdata append?


I want to send array of object data by formdata append. I'm getting an array to backend server but there is coming array of object by close string'[]' like this.so i want to remove this selfclose string. So please help me, how can i solve this issue?

I'm getting this one...........

varientDetails: ['{"index":0.40051008889580997,"sort":"45","sku":"5","waightorquantity":"100","Unit":"ghg","mrp":"gj","discount":"iy","price":"","stock":"","minstock":"","outofstock":""}']

but i want data like this:

varientDetails: [{"index":0.40051008889580997,"sort":"45","sku":"5","waightorquantity":"100","Unit":"ghg","mrp":"gj","discount":"iy","price":"","stock":"","minstock":"","outofstock":""}]

I'm using this approach

varientDetails.forEach(varient => {
  formData.append(`varientDetails[]`, JSON.stringify(varient))
})

Solution

  • FormData cannot send literal JavaScript objects. It can send...

    USVString or Blob (including subclasses such as File)

    Your objects must be serialised as JSON which is what you're doing. To handle that on the server, you would need to parse them. Assuming you're using something like Multer and the non-file fields are available on req.body...

    const variantDetails = req.body.varientDetails.map(json => JSON.parse(json))