在Angular 7中将一个对象转换为另一个对象

问题描述 投票:-1回答:3

我正在使用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"
   }
}
angular angular-material angular7
3个回答
1
投票

您可能希望将其转换为每个字段都是数组的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中已经存在该字段,则您正在将该消息添加到列表中。如果该字段不存在,请重新输入。


1
投票

您可以遍历fieldErrors数组,并将每个字段和消息分配给ServerResponse对象。

尝试以下代码:

let ServerResponse:any = {};
fieldErrors.forEach(item => {
    ServerResponse[item.field] = item.message;
});

0
投票
ServerResponse = errors.reduce((result, cur) => (result[cur.field] = cur.message, result), {});

但是您将丢失具有相同字段属性的项目

© www.soinside.com 2019 - 2024. All rights reserved.