0

On an Angular 7 application I have the following:

var name_key = "name";
var language_key = "language";
var type_key = "type"

Then an API returns the following JSON:

{
  "errors": {
    "language": [
      "language not found"
    ],
    "name": [
      "name not found",
      "name must not exceed 200 characters"
    ]
  }
}

I need to get the error messages for each key so that would be:

"name" > "name not found",
         "name must not exceed 200 characters"

"language" > "language not found"

"type" > NULL

How can I do this?

1 Answer 1

1

looks like that you need an array-like syntax allows you to access the object fields with variable keys:

const apiResponse = getApiData(); //your API response
const errorKeys = [name_key, language_key, type_key];
let errors = [];
for (let errKey of errorKeys) {
  errors.push(apiResponse.errors[errKey]);
}

P.S.: You don't usually use var keyword in typescript, because it messes with the scopes. Use let or const instead, here's why

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

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.