循环这个对象将key和value添加到FormData对象中

FormData

您可以使用以下代码循环该对象并将其添加到formData对象中:

const formData = new FormData();
const object = {
  "Policy": "eyJleHBpcmF0aW9uIjoiMjAyMy0wNy0yMFQwNjozMzoxMS4wNTZaIiwiY29uZGl0aW9ucyI6W3sia2V5IjoiZXhjaGFuZ2Utc3RvcmFnZS9hdmF0YXIvMTc2OTExNjUzOTA0MTYyMjY2NC5wbmcifSxbImNvbnRlbnQtbGVuZ3RoLXJhbmdlIiwwLDUyNDI4ODBdLHsiQ29udGVudC1UeXBlIjoiaW1hZ2UvcG5nIn0seyJidWNrZXQiOiJicm9rZXItZXhjaGFuZ2Utd2ViLXRlc3QifSx7IngtYW16LWFsZ29yaXRobSI6IkFXUzQtSE1BQy1TSEEyNTYifSx7IngtYW16LWNyZWRlbnRpYWwiOiJBS0lBNDZOSFIyQ01VUUZITkEyWS8yMDIzMDcyMC9hcC1zb3V0aGVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSx7IngtYW16LWRhdGUiOiIyMDIzMDcyMFQwNjI4MTFaIn1dfQ==",
  "x-amz-date": "20230720T062811Z",
  "x-amz-signature": "887a65fe1e95c711e8d647ffe682bbc33e3263e58aabdbc629a03ef4bf70857c",
  "key": "exchange-storage/avatar/1769116539041622664.png",
  "x-amz-algorithm": "AWS4-HMAC-SHA256",
  "Content-Type": "image/png",
  "x-amz-credential": "AKIA46NHR2CMUQFHNA2Y/20230720/ap-southeast-1/s3/aws4_request"
};

for (const [key, value] of Object.entries(object)) {
  formData.append(key, value);
}

// You can now use the formData object to send a POST request containing the data to your server or API endpoint.
Object.entries(object)是什么意思

Object.entries(object)是一个方法,它返回一个给定对象的所有可枚举属性的键值对数组。这个数组是一个二维数组,其中每个子数组都包含两个元素,第一个元素是属性的名称(键),第二个元素是属性的值。可以用这个方法来遍历一个对象的属性和值。

 可以使用for...in循环来遍历对象,将key和value添加到formData对象中:

const formData = new FormData();
for (const key in object) {
  const value = object[key];
  formData.append(key, value);
}

应用到此例子中如下:

const object = {
  "Policy": "eyJleHBpcmF0aW9uIjoiMjAyMy0wNy0yMFQwNjozMzoxMS4wNTZaIiwiY29uZGl0aW9ucyI6W3sia2V5IjoiZXhjaGFuZ2Utc3RvcmFnZS9hdmF0YXIvMTc2OTExNjUzOTA0MTYyMjY2NC5wbmcifSxbImNvbnRlbnQtbGVuZ3RoLXJhbmdlIiwwLDUyNDI4ODBdLHsiQ29udGVudC1UeXBlIjoiaW1hZ2UvcG5nIn0seyJidWNrZXQiOiJicm9rZXItZXhjaGFuZ2Utd2ViLXRlc3QifSx7IngtYW16LWFsZ29yaXRobSI6IkFXUzQtSE1BQy1TSEEyNTYifSx7IngtYW16LWNyZWRlbnRpYWwiOiJBS0lBNDZOSFIyQ01VUUZITkEyWS8yMDIzMDcyMC9hcC1zb3V0aGVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSx7IngtYW16LWRhdGUiOiIyMDIzMDcyMFQwNjI4MTFaIn1dfQ==",
  "x-amz-date": "20230720T062811Z",
  "x-amz-signature": "887a65fe1e95c711e8d647ffe682bbc33e3263e58aabdbc629a03ef4bf70857c",
  "key": "exchange-storage/avatar/1769116539041622664.png",
  "x-amz-algorithm": "AWS4-HMAC-SHA256",
  "Content-Type": "image/png",
  "x-amz-credential": "AKIA46NHR2CMUQFHNA2Y/20230720/ap-southeast-1/s3/aws4_request"
};

const formData = new FormData();
for (const key in object) {
  const value = object[key];
  formData.append(key, value);
}

现在formData对象中就包含了所有的key和value。

posted @ 2023-07-31 10:08  JackieDYH  阅读(60)  评论(0编辑  收藏  举报  来源