0

I am trying to use .find method but I am getting undefined.

const ValidationMsg = '[{        "enum": "RequiredInformationMissing",        "code": 101,        
"title": "Required information not provided",        "message": "The following information is needed 
to complete :" },    {        "enum": "RequiredInformationMissing_Details",        "code": 102,        
"title": "Required information not provided",        "message": "The following information is needed 
to complete the :"    }]';

const validationErrors : Array<ValidationError> = JSON.parse(ValidationMsg);
const x = validationErrors.find(ve => ve.code === (101 as number));

export class ValidationError {    
 code: number;
 message: string;
}

What am i doing wrong here?

Thanks, Sajesh

3
  • 2
    You are calling an object property with this. but validationErrors is a const variable defined one line above. Try const x = validationErrors.find(ve => ve.code === (101 as number)); Commented Dec 6, 2019 at 22:59
  • 1
    Array<ValidationError>[] is an array or arrays, and does not represent your data. After cleaning up the string, changing the type, and removing the this, I do get a value from the find via Typescript Playground (url link is too long to post in a comment). Commented Dec 6, 2019 at 23:00
  • 2
    Your code doesn't compile: validationErrors is of type Array<ValidationError>[] instead of Array<ValidationError>, your JSON is invalid, your string literal is not valid TypeScript. Fix all the compilation errors and use valid JSON, and the code will run fine. Note that 101 as number is redundant: 101 is a number. Commented Dec 6, 2019 at 23:25

2 Answers 2

1

Try this.

const x = validationErrors.filter(ve => ve.code === (101 as number))[0];

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks everyone, as you all pointed out correctly the issue was due to nested Arrays declaration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.