0

I have this simple JSON object:

var data = [{"some":25},{"stuff":12}]

I want to loop through this object to access both the key and it's value in each pair. Currently I know how to loop when a fixed key like:

var data = [{"host":"foo","url":"bar"},{"host":"foos","url":"bars"}]

$.each(data, function(i, item) {
     alert(data[i].host);
});​

What about if the key is different and I need to access it as well as the value?

1

3 Answers 3

3

You have an array of objects..so loop the array, then loop the keys of the object at that index:

for (var i = 0; i < data.length; i++) {
    for (var key in data[i]) {
        console.log(key + ":" + data[i][key]);
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

is there a jquery equivalent?
@MichaelSamuel -- You dont need jQuery...jQuery is JavaScript.
i know that already :) I prefer the jquery syntax more though
1

Not sure why you wanna use jQuery only, but:

$.each(data, function (i, obj) {
    $.each(obj, function (key, val) {
      // do what you want
    });
});

Comments

0

Here you go

var data = [{"host":"foo","url":"bar"},{"host":"foos","url":"bars"}]

$.each(data, function(i, item) {
     alert(data[i][key]);
});​

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.