简体   繁体   中英

How to loop through a simple JSON object in Javascript

Okay, so i'm aware there are similar questions on this on the site BUT all I have seen have people with an array INSIDE an array. So I'm just looking for a bit of help on a simple one that I just can't seem to grasp.

The JSON is being generated from a PHP file and looks something like this when retrieved via AJAX: {'name': 'Derick', 'email': 'email@example.com'} .

How can I loop through this response, using Javascript, to retrieve the value for, say, the 'name' key in the array?

code snippet:

response = {'name' : 'Derick', 'email' : 'email@example.com'};

If the response is only the given object, you can clearly get it by response['name'] .

If the response that you recieve is an array of objects like the one you wrote:

let result = [];
response.forEach(e => result.push(e['name']));

Should do what you want.

Your example code snippet is not an object array, but just an object. You would not loop thru it to access the data. But rather, access the data like this:

response.name and response.email

If your json object was an array, it would look something like this:

responses = [
    {
      'name' : 'Derick', 
      'email' : 'email@example.com'
    },
    {
      'name' : 'John', 
      'email' : 'johnsemail@example.com'
    }    
]

And you can loop through it such as:

for (x of responses) {
  console.log(x.name + ' ' + x.email);
}

Okay, after trying all these suggestions, nothing worked. Can't understand why. So the solution that has worked for me is this, (You can also find it on W3Schools, under 'Javascript JSON parse() method).

JSON.parse(response, function (key, value) {
  if (key == "name") {
      console.log(value);
  }
});

So basically, the code parsed the response (even though my response should have come back parsed. Redundant, I know) to a javascript object and loops through said object to find they key-value pair you're looking for.

This has worked for me although I have been unable, for the life of me, to deduce what may be wrong with simply using response.name or response['name'] to access them.

Anyway, hope this helps. A big thank you to all who took time out of their day to reach out to help a junior dev.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM