Home > Enterprise >  How to FormData append nested object
How to FormData append nested object

Time:03-20

how can post this array with form append:

data = [
    {
        "title":"title 1",
        "subTitle": "subTitle 1",
        "productId": "[1,2,3]"
    },
    {
        "title":"title 2",
        "subTitle": "subTitle 1",
        "productId": "[4,5,6]"
    },
    {
        "title":"title 3",
        "subTitle": "subTitle 1",
        "productId": "[7,8,9]"
    }
]

If I submit data as here : formData.append("data", JSON.stringify(this.data); I cannot get just id key in value productId

CodePudding user response:

You can try this-

data.forEach(item => {
            formData.append(`data[]`, JSON.stringify(item));
        });

and in the backend, you need to parse it for sending to the front end.

CodePudding user response:

Once your array has been "stringify" you need to use JSON.parse to access individual key

const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = obj.name;
</script>

Also looking at your array it you will have to do it like this with the array key

obj[0].productId
obj[1].productId
obj[2].productId
obj[3].productId

and from that point extract the array

 for (let i  = 0 ; i <  obj[3].productId.length ; i  )
{ 
 console.log(obj[3].productId[i]);

 }

Let me know if you need more info on it

  • Related