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.

5 Answers 5

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)

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

Comments

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

Comments

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

1 Comment

i agree all solutions look more work than simply using ide shortcuts like multiple cursors
7

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

4 Comments

Shouldn't it replace old properties with new one?
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.
Thanks. But then it would be possible to spread nested objects also, if needed.
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
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.