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'
}
John Smith
  • 91
  • 2
  • 5

5 Answers5

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);
});
pau.moreno
  • 4,407
  • 3
  • 35
  • 37
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.

Florian
  • 3,145
  • 1
  • 27
  • 38
1
jQUery has an each function

$.each(yourJsonObject, function(key, value) {
    //whatever processing
});
mikeq
  • 817
  • 5
  • 5
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/

rciq
  • 1,309
  • 10
  • 10
0

Using jquery

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

$.each(data, function(key, value){
    $(key).css('background-color', '#' + value);
})
Rob Cowie
  • 22,259
  • 6
  • 62
  • 56