1

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.

mr.boris
  • 3,667
  • 8
  • 37
  • 70

1 Answers1

6

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);
Reyno
  • 6,119
  • 18
  • 27
  • Many thanks, I've just tried same thing but in wrong way with `{...}` curly braces! Don't know why... – mr.boris Sep 15 '20 at 08:36