0

I am passing back a JSON object to jQuery. I need it to look through the JSON object and effectively do this.

$(key).css('background-color', '#'+val);

In php I would use a foreach loop. Does javascript have something similar? How would I go about doing this?

JSON

{
  '.one' : 'AAA',
  '.two' : 'BBB'
}
2

5 Answers 5

2

Take a look at the each function of jQuery:

var map = { 
  '.one': 'AAA', 
  '.two': 'BBB' 
};
$.each(map, function(key, val) { 
  $(key).css('background-color', '#'+val);
});
1

Use the jQuery.each method

jQuery.each(JSONobject, function(key, value) {
    $(key).css('background-color', '#'+value);
});

You can also use this instead of value in the function, because the function is executed in the context of each element.

1
jQUery has an each function

$.each(yourJsonObject, function(key, value) {
    //whatever processing
});
0

This will work:

var data = {
  '.one' : 'AAA',
  '.two' : 'BBB'
};

for (var key in data)
    if (typeof(data[key]) == 'string')
        $(key).css('background-color', '#' + data[key]);

A JSFiddle demo:

http://jsfiddle.net/r7s96/

2
  • you should use hasOwnProperty
    – Florian
    Jun 27, 2011 at 10:52
  • I wanted to filter out all non-string members. Adding another condition with hasOwnProperty would have no meaning here.
    – rciq
    Jun 27, 2011 at 10:59
0

Using jquery

var data = {
    '.one' : 'AAA',
    '.two' : 'BBB'
};

$.each(data, function(key, value){
    $(key).css('background-color', '#' + value);
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.