Vald
Vald

Reputation: 237

Add a value to an object inside a function

I need to create several instances of a slider. Each slider has two parameters : an element ID and an object that contains different options. All options are the same for all sliders, except one option (the speed on the example below)

var swiper1 = new Swiper ('#swiper1', {
    width: 200,
    distance: 10,
    slides: 5,
    preventClick: true
    // ... many others options
    speed: 300 
});

var swiper2 = new Swiper ('#swiper2', {
    width: 200,
    distance: 10,
    slides: 5,
    preventClick: true
    // ... many others options
    speed: 500 
});

// ... many others instances of Swiper

So to reduce the length of the code and avoid multiple copy/paste, I can do like that :

var options = {
    width: 200,
    distance: 10,
    slides: 5,
    preventClick: true
    // ... many others options
    speed: 500 
}

var swiper1 = new Swiper ('#swiper1', options)
var swiper2 = new Swiper ('#swiper2', options)
var swiper3 = new Swiper ('#swiper3', options)
// ...

But as I mentioned, only one parameter differs from one instance to another, so I need to do something like that :

var options = {
    width: 200,
    distance: 10,
    slides: 5,
    preventClick: true
    // ... many others options
}

var swiper1 = new Swiper ('#swiper1', {options, speed: 500})
var swiper2 = new Swiper ('#swiper2', {options, speed: 700})
var swiper3 = new Swiper ('#swiper3', {options, speed: 300})
// ...

But I don't know what is the correct way to do that

Upvotes: 0

Views: 259

Answers (3)

zero298
zero298

Reputation: 26930

Use Object.assign() to clone and overwrite properties selectively.

The spread syntax works as well, and I would tell you to use that, but if you might be worried about Edge and Safari support at the moment: Spread in object literals compatibility table

class Swiper {
  constructor(el, kwargs) {
    console.log(kwargs.speed);
  }
}

var options = {
  width: 200,
  distance: 10,
  slides: 5,
  preventClick: true
}

var swiper1 = new Swiper('#swiper1', Object.assign({}, options, {speed: 500}));
var swiper2 = new Swiper('#swiper1', Object.assign({}, options, {speed: 700}));
var swiper3 = new Swiper('#swiper1', Object.assign({}, options, {speed: 300}));

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138567

You are just missing the spread operator:

var swiper1 = new Swiper ('#swiper1', {...options, speed: 500})

That will copy all properties of options into the object literal you pass to the Swiper constructor.

Upvotes: 4

akuiper
akuiper

Reputation: 215137

You can use ... to create a new object containing options with an additional key speed:

new Swiper ('#swiper1', {...options, speed: 500})

Upvotes: 5

Related Questions