Javascript 如何根据 json 数组状态值使用条件语句给颜色
Javascript How to give color using conditional statement based on json array state value
如题所示,我想用chartColors变量根据json状态值指定颜色,根据json状态值给出颜色值
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
}
]
};
如果 A
在 functionStatus Array
中怎么办?我想给 backgroundColor 设置黄色。
我想创建一个条件语句并使用 chartColors 中的颜色将 "A": yellow
、"B": green
和 "C" gray
分配给数组值。
像下面这样尝试
保留颜色映射并使用 map
进行迭代以获取映射的颜色列表。
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
}
]
};
如题所示,我想用chartColors变量根据json状态值指定颜色,根据json状态值给出颜色值
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
}
]
};
如果 A
在 functionStatus Array
中怎么办?我想给 backgroundColor 设置黄色。
我想创建一个条件语句并使用 chartColors 中的颜色将 "A": yellow
、"B": green
和 "C" gray
分配给数组值。
像下面这样尝试
保留颜色映射并使用 map
进行迭代以获取映射的颜色列表。
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
}
]
};