Say I have an object like the following:
myObject{
name: '...',
label: '...',
menuSettings: {
rightAlignment: true,
colours: [...],
},
}
I would like to change the rightAlignment value to be false. I’m having quite a bit of trouble trying to access and modify just this value, without having to rewrite the rest of the object. I tried myObject.find(…) which didn’t quite suit, and now was trying
Object.assign(this.myObject, {menuSettings: {rightAlignment: false}});
Which wasn’t working because I’m guessing I didn’t access the property correctly. Is there any way to cleanly do this?
3
Answers
Just use the property accessor dot notation
.
:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#dot_notation
You’re pretty close there. If I understand correctly, you want to merge an existing object with the latest value from another object. Which you can achieve by doing as;
The way you’re doing currently, is not wrong though. but you’re replacing the entire
menuSettings
which then will remove yourmenuSettings.colours
.Or just access the property directly as per answer by Alexander.
You can update the rightAlignment property within menuSettings without rewriting the entire object. Here’s one way to achieve this using the spread syntax (…)