'How to update a variable within a varible in JavaScript [duplicate]
I have the following in my script
var mycolor = 'blue';
var option;
option = {
grid: {
color: mycolor
},
axis: {
color: mycolor
}
}
Then, I want to change it to red. usual way would be
option.grid.color = 'red'
option.axis.color = 'red'
This way it works; however, when I try mycolor='red', it is not updated in var option. How can I in one line change the color in option? For example, I want a command like option.*.color = red.
Thanks
Solution 1:[1]
Objects are "references" until you clone them, so this works:
var myColor = { color: 'blue' };
var option;
option = {
grid: myColor,
axis: myColor,
};
console.log(option); // { grid: { color: 'blue' }, axis: { color: 'blue' } }
myColor.color = 'red';
console.log(option); // { grid: { color: 'red' }, axis: { color: 'red' } }
Note that you don't reassign the myColor variable here, that would not work; instead you set the color property inside of the object which is used twice in the options, thus updating the value inside of the referenced object in the options as well.
Solution 2:[2]
What you try to do is not assign a variable to the option but just pass the value to the properties of the object.
You can use a setter in the option object.
option = {
grid: {
color: "red",
},
axis: {
color: "red",
},
set color(color) {
this.grid.color = color;
this.axis.color = color;
},
};
console.log(option.grid.color);
console.log(option.axis.color);
option.color = "blue";
console.log(option.grid.color);
console.log(option.axis.color);
Edit: update all the properties with name color in the object
option = {
grid: {
color: "red",
},
axis: {
color: "red",
},
set allColor(color) {
const setColor = obj => {
if (
typeof obj === "object" &&
!Array.isArray(obj) &&
obj !== null
) {
Object.keys(obj).forEach(key => {
if (key === "color") {
obj[key] = color;
}
setColor(obj[key]);
});
}
};
setColor(this);
},
get allColor() {
return null;
},
};
console.log(option);
option.allColor = "blue";
console.log(option);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | geisterfurz007 |
| Solution 2 |
