Convert JS Object to form data

前端 未结 18 1900
孤街浪徒
孤街浪徒 2020-11-29 17:22

How can I can convert my JS Object to FormData?

The reason why I want to do this is, I have an object that I constructed out of the ~100 form field valu

18条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 17:32

    Here is a short and sweet solution using Object.entries() that will take care of even your nested objects.

    // If this is the object you want to convert to FormData...
    const item = {
        description: 'First item',
        price: 13,
        photo: File
    };
    
    const formData = new FormData();
    
    Object.entries(item).forEach(([key, value]) => {
        formData.append(key, value);
    });
    
    // At this point, you can then pass formData to your handler method
    

    Read more about Object.entries() over here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

提交回复
热议问题