You have a couple of options.
Only assign to the one property:
obj.settings.theme = "white";
Use Object.assign
if you have an object of properties you want to assign (here I have just the one property, but you could have more):
Object.assign(obj.settings, {
theme: "white",
});
Object.assign
copies all of the own, enumerable properties from the objects provided as the second argument onward into the object provided as the first argument.
Use object spread syntax ...
on both the existing obj.settings
object and the new settings object into an anonymous, new object and assign that to obj.settings
:
obj.settings = { ...obj.settings, ...{ theme: "white" } };
Though there's no reason to do that here, just update the settings object you have. This option can be very useful in situations where you want to avoid ever modifying the existing object (state updates in various MVC libs, etc.).
In a self-answer it appears you wanted to move the assignment into the constructor, which you didn't mention in the question. I'd handle that by using parameter destructuring combined with destructuring default values and a parameter default (just a blank object):
class MyClass {
constructor({theme = "dark", confirmBtn = "ok", cancelBtn = "cancel"} = {}) {
this.settings = {
theme,
confirmBtn,
cancelBtn,
};
}
}
let obj= new MyClass({
theme: "white",
});
Live Example:
class MyClass {
constructor({theme = "dark", confirmBtn = "ok", cancelBtn = "cancel"} = {}) {
this.settings = {
theme,
confirmBtn,
cancelBtn,
};
}
}
// Settings not specified get defaulted
const obj1 = new MyClass({
theme: "white",
});
console.log(obj1.settings);
// No parameter at all gets all defaults
const obj2 = new MyClass();
console.log(obj2.settings);
You can also do it with Object.assign
, though I like the expressiveness of the defaults all being in the constructor signature:
class MyClass {
constructor(settings = {}) {
this.settings = Object.assign(
{},
{
theme: "dark",
confirmBtn: "ok",
cancelBtn: "cancel",
},
settings
);
}
}
let obj= new MyClass({
theme: "white",
});
Live Example:
class MyClass {
constructor(settings = {}) {
this.settings = Object.assign(
{},
{
theme: "dark",
confirmBtn: "ok",
cancelBtn: "cancel",
},
settings
);
}
}
// Settings not specified get defaulted
const obj1 = new MyClass({
theme: "white",
});
console.log(obj1.settings);
// No parameter at all gets all defaults
const obj2 = new MyClass();
console.log(obj2.settings);
constractor
? You meanconstructor
, right?