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.
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.
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 an object have JS? Summary. JavaScript objects have two types of properties: data properties and accessor properties.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With