TypeScript对象键处理:如何为错误集合添加数字索引键
Solution to Convert Errors Array to Indexed Object in TypeScript
You're currently returning an array for the errors field, but need to convert it into an object with numeric string keys starting from 1. Here's how to adjust your code to meet that requirement while aligning with your IConstraint interface:
Option 1: Iterative Approach (Closest to Your Original Code)
We'll replace the constraints array with an IConstraint object, then populate it with 1-indexed string keys as we loop through the error constraints:
export const formatErrors = (validationErrors: ValidationError[]): IErrorFormater[] => { let response: IErrorFormater[] = []; for (let error of validationErrors) { let field: string = error.property; // Initialize as an IConstraint object instead of an array const constraints: IConstraint = {}; let index = 1; // Start indexing from 1 for (let constraint in error.constraints) { if (error.constraints.hasOwnProperty(constraint)) { // Convert index to string to match IConstraint's key type constraints[index.toString()] = error.constraints[constraint]; index++; } }; response.push({ field, errors: constraints }); } return response; }
Option 2: Functional Approach (More Concise)
Using map and reduce makes the code cleaner while achieving the same result:
export const formatErrors = (validationErrors: ValidationError[]): IErrorFormater[] => { return validationErrors.map(error => { // Convert constraint values to an indexed object const errors: IConstraint = Object.values(error.constraints).reduce((acc, err, idx) => { acc[(idx + 1).toString()] = err; // idx starts at 0, so add 1 for 1-based indexing return acc; }, {} as IConstraint); return { field: error.property, errors }; }); }
Result
Both approaches will return the desired structure:
[ { "field": "departament_name", "errors": { "1": "O nome do departamento precisa ser do tipo String", "2": "departament_name must be an UUID" } } ]
Key notes:
- We're using
index.toString()because yourIConstraintinterface requires string keys (numeric keys in objects are automatically coerced to strings, but explicitly converting ensures type safety). - The 1-based indexing is achieved by starting our counter at 1, or adding 1 to the zero-based index from
reduce.
内容的提问来源于stack exchange,提问作者Ming
相关产品推荐
相关产品推荐

