Search code examples
angularangular-materialangular7

Convert one object to another in Angular 7


I am using Angular 7 and I am getting all details into 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

I want to convert it into the

ServerResponse = {
   "studentName" {
        "Program Name is mandatory"
    },
    studentDesc {
       "Student Description is mandatory"
   }
}

Solution

  • You might probably want to convert it into a json with each field being an array, like below:

    ServerResponse = {
        studentName: [
            "Length of characters should be between 1 to 255",
            "Program Name is mandatory"
        ],
        studentDesc: [
            "Student Description is mandatory"
        ]
    }
    

    In this way, multiple error messages for the same field can be fit into the same key.

    You can loop through the fieldErrors array and manually assign the values.

    let ServerResponse = {};
    fieldErrors.forEach(fieldError => {
        if (ServerResponse[fieldError.field]) {
            ServerResponse[fieldError.field].push(fieldError.message);
        } else {
            ServerResponse[fieldError.field] = fieldError.message;
        }
    });
    

    If the field is already present in ServerResponse, you are adding the message to the list. If the field is not present, make a new entry.