Search code examples
json2html

How can I apply differnt styles when transforming data using json2html based on data value?


I am trying to format data using json2html

data is as follows:

            var data = [
                {'name':'Bob','level':1},
                {'name':'Frank','level':2},
                {'name':'Bill','level':3},
                {'name':'Robert','level':1},
                {'name':'Chen','level':3},
                {'name':'Will','level':2}
            ];

transform is as follows:

var transform = {"tag":"div","class":"player","children":[
                {"tag":"div","class":"p-name","html":"${name}"},
                {"tag":"div","style":"background:yellow","class":"p-level","html":"${level}"}
]}

but I need the background color of the div above to be colored based on level, as an example level 1 - yellow, level 2 - green, level 3 - red.


Solution

  • simple .. use an inline function to set the style

    var transform = {"tag":"div","class":"player","children":[
                {"tag":"div","class":"p-name","html":"${name}"},
                {"tag":"div","style":function(){
    
                     var color;
    
                     switch(this.level) {
                       case 1: color = 'yellow';
                       case 2: color = 'green';
                       case 3: color = 'red';
                     };
    
                     return('background-color:' + color);
    
                },"class":"p-level","html":"${level}"}
    ]};
    

    OR best practice would be to set the class and apply the style in css like so

    var transform = {"tag":"div","class":"player","children":[
                {"tag":"div","class":"p-name","html":"${name}"},
                {"tag":"div","class":"p-level color-level-${level}","html":"${level}"}
    ]};
    
    .color-level-1 {background-color:yellow;}
    .color-level-2 {background-color:green;}
    .color-level-3 {background-color:red;}