11

Is there some kind of shorthand for this?

object.position.x = position.x
object.position.y = position.y
object.position.z = position.z

object.rotation.x = rotation.x
object.rotation.y = rotation.y
object.rotation.z = rotation.z

Thanks for your time.

Damjan Pavlica
  • 31,277
  • 10
  • 71
  • 76

5 Answers5

12

Yes you can use Object.assign().

var obj = {}
var position = {x: 1, y: 2, z: 3}
var rotation = {x: 1, y: 2, z: 3}

obj.position = Object.assign({}, position);
obj.rotation = Object.assign({}, rotation);

console.log(obj)

If you only want to take specific properties from object you can create your pick function using map() to get array of objects and later use spread syntax to assign each object.

var obj = {}
var position = {x: 1, y: 2, z: 3}
var rotation = {x: 1, y: 2, z: 3}

function pick(obj, props) {
  return props.map(e => ({[e]: obj[e]}))
}

obj.position = Object.assign({}, ...pick(position, ['x', 'y']));
obj.rotation = Object.assign({}, ...pick(rotation, ['x', 'y', 'z']));

console.log(obj)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
9

You could use a direct approach by assigning the objects directly,

object.position = position;
object.rotation = rotation;

or with an array and the keys with iterating the properties.

['x', 'y', 'z'].forEach(function (k) {
    object.position[k] = position[k];
    object.rotation[k] = rotation[k];
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
8

My advice: DON'T USE ANY "CLEVER" LOOPS AND DYNAMIC SH*T

Reasons:

  1. It's just a few lines, not a ton of lines, don't do overengineering
  2. It's so much readable, that even IDE can help you with autosuggestions
Engineer
  • 47,849
  • 12
  • 88
  • 91
8

With ES6 Spread Operator you can do it easier in one line, for the question sample:

object = {...object, position, rotation}

Just notice it will replace new properties with old one

Mohsen
  • 4,049
  • 1
  • 31
  • 31
  • 1
    Shouldn't it replace old properties with new one? – Damjan Pavlica Dec 24 '19 at 10:07
  • 1
    Should be, just notice if you add some properties ( for example add object.rotation.a ) to old property that not exists in new one they will lose. – Mohsen Dec 24 '19 at 18:04
  • Thanks. But then it would be possible to spread nested objects also, if needed. – Damjan Pavlica Dec 24 '19 at 21:23
  • sure, `rotation = { ...object.rotation, ...rotation }` , merge old `object.rotation` and new `rotation` before pass to object, by the way we have all `object.rotation` properties with replaced `rotation` values – Mohsen Dec 25 '19 at 19:21
0

You can also use a for...in loop, it's simple and quite readable. Example:

for ( const property in position ) {
    object.position[property] = position[property];
}

MDN reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

Ignacio Segura
  • 678
  • 8
  • 15