0

I have an Ajax call which returns a JSON response and i'm loading the response using an array

var results = { 
    "appointmentrequired": {"name": "Appointment Required?"},
};

success: function(data) {
    $.each(results, function(key, value) {
        // show results from `data` here
    });
}

But I'm not sure how to access the results inside the array loop.

I've tried

console.log(data[key]);
console.log(data.key);

But both return undefined

0

3 Answers 3

2

If you console.log() both key and value you should be able to see what's being provided to the function arguments.

As such, either data[key].name or value.name is what you need.

// mock AJAX response data
var data = {
  "appointmentrequired": {
    "name": "Appointment Required?"
  },
};

// in AJAX response handler
$.each(data, function(key, value) {
  console.log('key:', key)
  console.log('value:', value);

  console.log('Name from key:', data[key].name);
  console.log('Name from value:', value.name);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

9 Comments

i'm trying to retrieve the value from data in my ajax request
Ok, so change results to data. I did it this way so it worked in the snippet given the example in your question
so, that would mean i need to use data[key] to retrieve the value from the ajax request with the key in results?
In which case you've either got a typo somewhere or the format of the response is not what you expect it to be. Given the data structure you provide in the question this works fine, as can be seen in the snippet. If it doesn't work for you please edit the question to give a more accurate example of your code, and the response.
if I console.log(data["appointmentrequired"]); i get undefined. My JSON response looks like {"appointmentrequired":"yes"}
|
0

You need to iterate over data returned from the api, not results:

success: function(data) {
    $.each(data, function(key, value) {
       console.log(key, value) // appointmentrequired {name: "Appointment Required?"}
    });
}

2 Comments

i want to iterate over the results array to show all the information in there, and then find whether data returns a value - if it does, display it, if not just display "-"
@charlie There is no Array shown in your results object
-1

$.each run on arrays

You want to explore let keysArr = Object.keys(data)

1 Comment

From jQuery docs: "jQuery.each( array, callback ): A generic iterator function, which can be used to seamlessly iterate over both objects and arrays."

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.