0

I am trying to display the value of the key from the api response. my code looks like

if(response[0].status == "Success")
            {
                alert('success');
            }
            else
            {
                var texts = "";
                for (reasons in response[0].error_reason) {
                    texts += reasons+";";
            }
                alert(texts);
            }

My key here is "item" and its value is "Choose an valid item" . i want to print the value in alert. BUt when i try to alert its displaying the key(item) not the value. how can i display key value here. also there can be multiple keys like items.

1
  • 2
    You can try: texts += response[0].error_reason[reasons] + ";";. Commented Feb 5, 2015 at 7:30

1 Answer 1

1

As you have mentioned, the foreach loop in JavaScript iterates through keys, that means that the reasons variable in your code will be set to a new key after each iteration. In order to access the value, you simply use the reasons variable as the index like this:

var texts = "";
for (reasons in response[0].error_reason) {
    texts += reasons + " = " + response[0].error_reason[reasons] +";";
}    

However, you should be careful with foreach in Javascript, because it iterates through all the properties of an object, including the functions of the object's prototype, e.g. you will get indexOf as a key in your loop eventually. To avoid that, you should check the value's type:

var texts = "";
for (reasons in response[0].error_reason) 
    if(typeof(response[0].error_reason[reasons]) !== 'function')
        texts += reasons + " = " + response[0].error_reason[reasons] +";";

This should work as intended.

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.