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.

1
  • 2
    configs: { image: 'pic.png', ...props.filters } Commented Sep 15, 2020 at 8:33

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks, I've just tried same thing but in wrong way with {...} curly braces! Don't know why...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.