Assigning properties to multiple objects

Is there any shortcut 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

Thank you for your time.

+6
source share
3 answers

You can use a direct approach by directly assigning objects,

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

or with an array and keys with iteration of properties.

['x', 'y', 'z'].forEach(function (k) {
    object.position[k] = position[k];
    object.rotation[k] = rotation[k];
});
+9
source

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)
Run codeHide result

If you only want to get certain properties of an object, you can create your selection function with map()to get an array of objects, and then use the distribution 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)
Run codeHide result
+7
source

: "" LOOPS SH * T

:

  • , , overengineering
  • , IDE
0
source

Source: https://habr.com/ru/post/1016570/


All Articles