gpt4 book ai didi

javascript - 如何将嵌入/嵌套的 FormGroup 转换为 FormData

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:57 26 4
gpt4 key购买 nike

这是我的表单组:

this.shopGroup = this.fb.group({
_user: [''],
name: ['', Validators.compose([Validators.required, Validators.maxLength(60)])],
url_name: [''],
desc: ['', Validators.compose([Validators.required, Validators.maxLength(600)])],
photos: [''],
currency: ['Real'],
language: ['Português do Brasil'],
address: this.fb.group({
zipcode: ['', Validators.compose([Validators.required, Validators.pattern('[0-9]{5}[\-]?[0-9]{3}')])],
street: ['', Validators.compose([Validators.required, Validators.maxLength(70)])],
number: [null, Validators.compose([Validators.required, Validators.max(99999)])],
complement: ['', Validators.maxLength(30)],
district: ['', Validators.compose([Validators.required, Validators.maxLength(60)])],
state: ['', Validators.required],
city: ['', Validators.compose([Validators.required, Validators.maxLength(70)])]
}),
status: [true],
created_at: [new Date()],
updated_at: [new Date()]
});

我需要将它转换为 FormData,因为我正在将图像上传到服务器(Multer 包),但是,我不确定如何像处理 中的新对象一样处理 address 组>shopGroup 表单数据。这是我正在做的从 FormGroup 转换为 FormData 的操作(地址无效):

const shopData: any = new FormData();
shopData.append('name', shopGroup.get('name').value);
shopData.append('zipcode', shopGroup.get('address').get('zipcode').value);
...

如何进行转换(Json 到 FormData)并处理嵌入/嵌套对象,如 address

最佳答案

好的,我找到了一个将 JSON 对象转换为 FormData 的函数:

convertJsontoFormData(jsonObject: Object, parentKey, carryFormData: FormData): FormData {

const formData = carryFormData || new FormData();
let index = 0;

for (var key in jsonObject) {
if (jsonObject.hasOwnProperty(key)) {
if (jsonObject[key] !== null && jsonObject[key] !== undefined) {
var propName = parentKey || key;
if (parentKey && this.isObject(jsonObject)) {
propName = parentKey + '[' + key + ']';
}
if (parentKey && this.isArray(jsonObject)) {
propName = parentKey + '[' + index + ']';
}
if (jsonObject[key] instanceof File) {
formData.append(propName, jsonObject[key]);
} else if (jsonObject[key] instanceof FileList) {
for (var j = 0; j < jsonObject[key].length; j++) {
formData.append(propName + '[' + j + ']', jsonObject[key].item(j));
}
} else if (this.isArray(jsonObject[key]) || this.isObject(jsonObject[key])) {
this.convertJsontoFormData(jsonObject[key], propName, formData);
} else if (typeof jsonObject[key] === 'boolean') {
formData.append(propName, +jsonObject[key] ? '1': '0');
} else {
formData.append(propName, jsonObject[key]);
}
}
}
index++;
}
return formData;
}
isArray(val) {
const toString = ({}).toString;
return toString.call(val) === '[object Array]';
}

isObject(val) {
return !this.isArray(val) && typeof val === 'object' && !!val;
}

关于javascript - 如何将嵌入/嵌套的 FormGroup 转换为 FormData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53026879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com