Home > Net >  Javascript How to give color using conditional statement based on json array state value
Javascript How to give color using conditional statement based on json array state value

Time:11-12

As the title suggests, I want to use the chartColors variable to specify colors according to the json state value and give the color value according to the json state value.


 console.log(functionInfo);  // Array(6) : 0 : Lactobacillus  1 :Lactobacillus  2 : Glacagon 3 : toothpaste  4 : toothpaste  5 : Glacagon
 console.log(functionStatus) // Array(6) : 0 : "A"            1 : "A"           2 : "B"      3 :  "C"        4 :  "B"        5 : "C" 

  let chartColors = {
        yellow: 'rgb(244, 208, 104)', // A 
        green: '#4CC26F', // B 
        gray: '#EBEBEB' // C 
      };


 const Function = {
        datasets: [
          {
            backgroundColor: [],  ,
            data: functionInfo, // Lactobacillus Lactobacillus Glacagon toothpaste toothpaste Glacagon
          },
     
        ],
        
      };

What if A in functionStatus Array? I want to give yellow to the backgroundColor .

I would like to create a conditional statement and assign "A": yellow, "B": green, and "C" gray to the array values ​​using the colors in chartColors.

CodePudding user response:

Try like below

Keep a color map and iterate using map to get the mapped colors list.

const colorMap = {
    A: "yellow",
    B: "green",
    C: "gray"
};

let chartColors = {
    yellow: "rgb(244, 208, 104)", // A
    green: "#4CC26F", // B
    gray: "#EBEBEB" // C
};

const Function = {
    datasets: [
        {
            backgroundColor: functionStatus.map((colorCode) => chartColors[colorMap[colorCode]]),
            data: functionInfo // Lactobacillus Lactobacillus Glacagon toothpaste toothpaste Glacagon
        }
    ]
};

  • Related