Reputation: 451
There is a function that requires and setting object.
var opt = {
height: 300,
maxLength: 4000,
valueChangeEvent: "change",
placeholder: "",
}
$(selector1).doStuff(opt);
$(selector2).doStuff(opt);
$(selector3).doStuff(opt);
$(selector4).doStuff(opt);
The thing is that the placeholder should be different every time. Currently, I create this opt object with every call but it seems ugly. Is there a way to pass this opt object while just changing one property?
Upvotes: 4
Views: 1275
Reputation: 78
you can used spread syntax, allows an iterate are expected in this case:
$(selector1).doStuff({...opt, placeholder: 'Everything' })
read more about it here
Upvotes: 0
Reputation: 50884
You could write a function which produces opt
for you. In this function, you can pass the placeholder as an argument to be used like so:
const createOpt = (placeholder = '') => ({
height: 300,
maxLength: 4000,
valueChangeEvent: "change",
placeholder
});
console.log(createOpt("x"));
console.log(createOpt("y"));
console.log(createOpt());
Upvotes: 1
Reputation: 198446
Use the spread syntax like this:
let opt = {
height: 300,
maxLength: 4000,
valueChangeEvent: "change",
placeholder: "",
}
console.log({...opt, placeholder: "foo"});
console.log({...opt, placeholder: "bar"});
Or Object.assign
like this:
let opt = {
height: 300,
maxLength: 4000,
valueChangeEvent: "change",
placeholder: "",
}
console.log(Object.assign({}, opt, { placeholder: "foo" }));
console.log(Object.assign({}, opt, { placeholder: "bar" }));
Both of these solutions are non-destructive (i.e. they don't change opt
). If you want a destructive solution, leave out the first argument from Object.assign
.
Upvotes: 4
Reputation: 164924
You can use your opt
object as a template like this
$(selector1).doStuff({...opt, placeholder: 'different every time' })
The ...
operator destructures the original opt
object, then any further other properties are added to the result, replacing anything that conflicts.
Upvotes: 6