【问题标题】:how to append array of objects to formData如何将对象数组附加到 formData
【发布时间】:2023-01-06 23:14:45
【问题描述】:

我有一个动态表单,我将所有值保存在一个 useState 中,名称为 formFields 并像这样输出:

   {
      title: "aaa",
      description: "bbb",
      second_description: "ccc",
      step_number: 1,
      image: null,
    },
   {
      title: "zzz",
      description: "xxx",
      second_description: "eee",
      step_number: 2,
      image: null,
    }
]

我应该保存这个对象数组并像这样作为 POST 请求发送:

{
 steps: [
         {
      title: "aaa",
      description: "bbb",
      second_description: "ccc",
      step_number: 1,
      image: null,
    },
   {
      title: "zzz",
      description: "xxx",
      second_description: "eee",
      step_number: 2,
      image: null,
    }

    ]
}

但是使用这段代码我不能在 steps[] 中附加这个对象

   formFields.forEach((item) => {
      formData.append("steps[]", item);
    });

并在控制台中显示如下: steps: Array [ "[object Object]", "[object Object]" ]

对象保存为stringsteps! , 但我想保存对象 我该怎么做?

【问题讨论】:

  • 这回答了你的问题了吗? Can I append an array to 'formdata' in javascript?
  • @Konrad 和JSON.stringify |像这样保存:"{\"title\":\"aaaaaaaaaa\",\"description\":\"aaaaaaaaa\",\"second_description\":\"aaaaaaaaaaaaaaaaaaaaaaaaaa\",\"step_number\":1,\"image\":null}"

标签: reactjs react-hooks


【解决方案1】:

这回答了你的问题了吗?

let formFields = [{
      title: "aaa",
      description: "bbb",
      second_description: "ccc",
      step_number: 1,
      image: null,
    },
   {
      title: "zzz",
      description: "xxx",
      second_description: "eee",
      step_number: 2,
      image: null,
    }]
;

let formData = {};
formData.steps = [];

formFields.forEach((item) => {
    formData.steps.push(item);
});

JSON.stringify(formData);

//output 

'{"steps":[{"title":"aaa","description":"bbb","second_description":"ccc","step_number":1,"image":null},{"title":"zzz","description":"xxx","second_description":"eee","step_number":2,"image":null}]}'

【讨论】:

  • 当我作为 POST API 发送时,步骤不会附加到 formData
猜你喜欢
  • 1970-01-01
  • 2020-12-03
  • 2020-06-23
  • 2019-09-21
  • 1970-01-01
  • 1970-01-01
  • 2015-11-12
  • 2019-03-05
  • 2014-06-13
相关资源
最近更新 更多