Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple object properties assignment in Javascript

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.

like image 312
Damian Pavlica Avatar asked Apr 16 '17 11:04

Damian Pavlica


People also ask

How properties are assign to an object in JavaScript?

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method.

How do you assign object properties?

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

How many properties can a JavaScript object have?

How many properties can an object have JS? Summary. JavaScript objects have two types of properties: data properties and accessor properties.


2 Answers

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)
like image 162
Nenad Vracar Avatar answered Sep 30 '22 14:09

Nenad Vracar


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

like image 28
Mohsen Avatar answered Sep 30 '22 12:09

Mohsen