Assigning multiple properties to objects in Javascript

Can you show me a quicker way to do 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

Your assistance is greatly appreciated.

Answer №1

A viable option is to utilize the Object.assign() method.

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 are looking to extract specific properties from an object, you can create a custom function using map() to generate an array of objects and then use the spread syntax for assignment.

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)

Answer №2

One method is to assign the objects directly for a more direct approach,

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

Alternatively, you could use an array and iterate through the keys to assign properties.

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

Answer №3

Here is my tip: Avoid complicated loops and dynamic code

Why:

  1. Simplicity is key, don't overcomplicate things with excessive lines of code
  2. Clean code is easier to understand and work with, even IDEs can assist you with suggestions

Answer №4

One simple way to achieve this task is by using the ES6 Spread Operator in just a single line of code. Here's how you can do it for the question sample:

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

It's important to note that this operation will overwrite existing properties with the new ones.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to prevent code execution until a value is returned by $.get?

My attempt to read data from a file and store it in an array using jQuery's get function has hit a snag. Since the get function is asynchronous, the code that comes after the $.get call runs before the data is defined. How can I make sure that the cod ...

What is the best way to retrieve information from a JavaScript file?

Learning.vue <template> <div> <button @click="test()">test</button> </div> </template> <script> import records from './records.js' export default { data () { return { ...

How can I apply a class to the pre and code elements in Redactor?

I've been struggling for days to figure out how to add a class to the formatting option element within Redactor. By default, the "Code" formatting option wraps content in either <pre></pre> or <code></code> HTML elements. Howe ...

I encounter obstacles when trying to execute various tasks through npm, such as downloading packages

Currently, I am facing an issue while trying to set up backend development using node.js on my personal computer. The problem lies with the npm command as it is not functioning correctly. Despite successfully installing a file without any errors, I am unab ...

Creating a Visual Presentation with Background Image Transition in HTML, CSS, and JavaScript

Seeking assistance in setting up a basic background image slideshow on my website. I have been unable to locate a suitable tutorial online, so I'm reaching out here for guidance. HTML: <body> <h3>Welcome!</h1> <p>Lorem i ...

JavaScript fails to function in an HTML file

I am facing an issue where my JavaScript code works perfectly in JSFiddle, but when I copy it into an HTML file, it doesn't function as expected. Despite searching through other related posts, I have been unable to find a solution for this specific pr ...

Use jQuery to create a price filter that dynamically sets slide values based on the filter object

I'm currently utilizing the jQuery slide filter to sort products based on price. The filtering value is set within the script, but I am interested in dynamically setting it based on the highest/lowest number found on my page using a data attribute. D ...

"Vue.js integrates seamlessly with Tracking.js for advanced tracking

Has anyone successfully integrated the tracking.js library into a vueJS application? I followed these steps to install the package: npm install --save tracking After that, I defined the library in my main.js file like this: import tracking from 't ...

Exploring the World of Dynamic Table ID Access in Rails 5 with Coffeescript

Within my Index view, I have a table that I want to dynamically populate with an ID. This is what I've attempted so far: id="table_<%= @controller_name %>" The method in my controller looks like this: def get_controller_name @controller_nam ...

Utilizing the HasMany - BelongsTo relationship in Ember.js with the RESTAdapter

Can anyone provide guidance on creating a has many belongs to relationship using RESTAdapter in EmberCLI? I am working on a project where a card (representing a Twitter user) can have multiple hashtags associated with it. Here are my model definitions: / ...

Is there a way to assign the chosen option from a dropdown list to an input field in Vue 3?

I am working with a list that is returned from an API request. I have a text input field where I can search for items in the list, and the results are displayed dynamically as I type. My goal is to be able to select an option from the list and display the ...

Incorporating HTML5 Video Using an AJAX Request

I am attempting to fetch a video using an ajax query, but it seems that the video player control buttons are missing. Here is the code I am using: $.ajax({ context: document.body, url: "/?get=json&act=video", type: "get", success: fu ...

Is the form always being processed by onsubmit and confirm?

Apologies if this question has been asked before. I am currently working on a form where I ask the user to confirm an action, but it's not functioning as expected. The form proceeds regardless of whether the user clicks ok, cancel, or even closes the ...

What is the best way to save a JavaScript array in HTML5 local storage?

I am looking for a way to store an array of inputs using the local storage feature of HTML5. Currently, I am able to add weight inputs to the array, but they disappear once I refresh the page. Can anyone assist me with this? <!DOCTYPE html> <html ...

Tips for aligning meshes to the left and ensuring responsiveness in three.js

Currently working on a website using three.js, I'm facing an issue where I can't seem to align and make the mesh responsive simultaneously. My current approach to alignment is: cube.position.x = -20 However, when I try resizing the window, the m ...

What is the best way to choose all checkboxes identified by a two-dimensional array?

I need help with a question div setup that looks like this: <div class="Q"> <div id="Q1"><span>1. </span>Which of the following have the same meaning?</div> <div class="A"><input type="checkbox" id="Q1A1Correct" /& ...

Django: creating a custom dropdown input field for the receiver that is tailored to the sender

I am facing an issue with creating a dropdown list for the receiver without including the sender's id/name. This is different from a chained dropdown which has already been addressed in previous discussions. I believe that using ajax might be the solu ...

Generate a unique identifier for the HTML content

Is there a more efficient way to assign unique id tags to certain words using vanilla javascript? For example: <p>All the king's horses ran away.</p> For instance, "All" would have the id "term1", "King's" would have "term2", and ...

Sending data using jQuery to a web API

One thing on my mind: 1. Is it necessary for the names to match when transmitting data from client to my webapi controller? In case my model is structured like this: public class Donation { public string DonorType { get; set; } //etc } But the f ...

Encountering an "Unknown Provider" issue while trying to inject a provider from another module into a

Having trouble with two modules, module A and module B, that are interdependent. Module A is currently in the process of being bootstrapped. I need to inject a provider from module A into the config block of module B. Unfortunately, I keep getting an erro ...