简体   繁体   中英

access objects from json

I have an ajax call that receives a json encoded object on return.

success: function (response) {
jsonArrayResponse =  jQuery.parseJSON(response["data"]);
autoSearchValue = jsonArrayResponse['autoresult'];

I want to be able to access the different parts of the decode. This is some sample return

{"success":true,"message":null,"messages":null,"data":"{\"errorText\":\"\",\"autoresult\":[{\"firstname\":\"Annon\",\"lastname\":\"Brooks\",\"date_of_birth\":\"1975-12-23 00:00:00\",\"id\":\"1\"},{\"firstname\":\"Josh\",\"lastname\":\"Ferns\",\"date_of_birth\":\"2000-09-02 00:00:00\",\"id\":\"2\"},
{\"firstname\":\"Alan\",\"lastname\":\"Templeton\",\"date_of_birth\":\"1975-08-02 00:00:00\",\"id\":\"3\"}}]}

I've found that I can access the firstname by

autoSearchValue[0]['firstname'];

but I can't figure out how to loop through the other firstname values. I'm guessing it's straightforward once you know how.

Any help would be great thanks

autoSearchValue is an array. Just use an index in a loop:

for (let index = 0; index < autoSearchValue.length; index++) {
  autoSearchValue[index]['firstname'];
}

Maybe try to loop throught the length of the json object? Each loop will increment the counter since you get the first name with autoSearchValue[0]['firstname'] then find the next one with autoSearchValue[1]['firstname'] until the length is reached.

You can access by iteratig over the object. As an option you can use map function to iterate over the array, the callback function will receive current value on the argument which you can either modify or process

   autoSearchValue.map((value) => {
       console.log(value.firstname)
    })

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