简体   繁体   中英

JavaScript loop through a JSON.stringify(data)

I want to Loop through my data and do stuff.

Following

var stuff = JSON.stringify(data)

Returns me something like this:

{"0":"data:image/png;base64,testi,"2":"data:image/png;base64, testi2, ....

I Need to Loop through that but the Approach I did, did not work.

        for (var i = 0; i < stuff.length; i++) {
            $('#img-thumb-id'+i).attr('src', data[i]);
        }

Edit

I am using JSON.stringify because console.log(data) just returned me object object which I cant work with.

If you want to loop through data , then you need to loop through data .

Converting it to a JSON document will give you a string. You can't (usefully) loop through that.

Since converting it to JSON shows that it is an object, not an array, it is unlikely to have a length , so you'll need to use a method to loop over objects .

In order to loop over object keys you can use:

var keys = Object.keys(data);

Which gives you an array with all the keys in your object. Now you can loop the values by:

for (var i = 0; i < keys.length; i++) {
   var value = data[key];
   // your code here...
}

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