Search code examples
javascriptobjectvariablesecmascript-2016

Javascript: assign object to variable


I have an existing object with some properties:

var props = {
  filters: {
    brightness: 0,
    opacity: 1,
  }
}

So, I want to assign filter properties of this object to another object during variable declaration:

var sprite = {
  configs: {
    image: 'pic.png',
    // <- assign `props.filters` right here
  }
}

As there result I want to get such object:

{
  configs: {
    image: 'pic.png',
    brightness: 0,
    opacity: 1,
  }
}

I can do it just after sprite variable declaration like this:

Object.assign(sprite.configs, props.filters);

But is it possible to assign properties of another object during variable declaration?

It would be very convenient in case there are many-many props in one object and JS will allow to implement such assignment during variable declaration to eliminate redundant post processing.


Solution

  • You can use the spread operator to "spread" the values of props inside the sprite variable.

    const props = {
      filters: {
        brightness: 0,
        opacity: 1,
      }
    };
    
    const sprite = {
      configs: {
        image: 'pic.png',
        ...props.filters,
      }
    };
    
    console.log(sprite);