我正在使用Angular 7,并且正在将所有详细信息放入const fieldErrors = error.error.fieldErrors;
中
0:
code: "Size"
field: "studentName"
message: "Length of characters should be between 1 to 255"
resource: "studentDto"
__proto__: Object
1:
code: "NotBlank"
field: "studentName"
message: "Program Name is mandatory"
resource: "studentDto"
__proto__: Object
2:
code: "NotBlank"
field: "studentDesc"
message: "Student Description is mandatory"
resource: "studentDto"
__proto__: Object
length: 3
我想将其转换为
ServerResponse = {
"studentName" {
"Program Name is mandatory"
},
studentDesc {
"Student Description is mandatory"
}
}
您可能希望将其转换为每个字段都是数组的json,如下所示:
ServerResponse = {
studentName: [
"Length of characters should be between 1 to 255",
"Program Name is mandatory"
],
studentDesc: [
"Student Description is mandatory"
]
}
这样,可以将同一字段的多个错误消息放入同一密钥。
您可以遍历fieldErrors
数组并手动分配值。
let ServerResponse = {};
fieldErrors.forEach(fieldError => {
if (ServerResponse[fieldError.field]) {
ServerResponse[fieldError.field].push(fieldError.message);
} else {
ServerResponse[fieldError.field] = fieldError.message;
}
});
如果ServerResponse
中已经存在该字段,则您正在将该消息添加到列表中。如果该字段不存在,请重新输入。
您可以遍历fieldErrors数组,并将每个字段和消息分配给ServerResponse对象。
尝试以下代码:
let ServerResponse:any = {};
fieldErrors.forEach(item => {
ServerResponse[item.field] = item.message;
});
ServerResponse = errors.reduce((result, cur) => (result[cur.field] = cur.message, result), {});
但是您将丢失具有相同字段属性的项目