Modifying JavaScript object values using the Object() constructor

My background is in Groovy, which has similar syntax to JavaScript. In Groovy, I can easily copy values from one map to another like this:

def myMap1 = {};
def myMap2 = {};

myMap1["key1"] = "value1";
myMap1["key2"] = "value2";
myMap1["key3"] = "value3";

myMap1.each() { key, value =>
    myMap2[key] = value;
}

However, dealing with prototypes in JS has been challenging for me. It seems like accessing key/value pairs without prototyping is possible using Object(), but when trying to update data, I encountered the following issue:

var existingData = {"foo":"thing","bar":"otherThing","baz":"whatever"};
var update = {"foo":"newStuff","bar":"thisChanged","baz":"arghh"};

for (const [ key, value ] of Object.entries(update)) {
    console.log("Old value is " + existingData[key]);
    existingData[key] = value;
    console.log("Setting " + existingData[key] + " to " + value);
}

I expected this code to work, but it resulted in undefined values being displayed in the console. It seems that existingData[key] is not referencing the key correctly. How can I fix this and update the values based on the keys in the second object?

Answer №1

for (const property in object1) {
    object2[property] = object1[property];
}

By the way, have you ever considered using Object.assign()? It actually creates a new object instead of modifying existing ones.

let updateValues = { "property1": "value1", "property2": "value2" };
let updatedObject = Object.assign({}, originalObject, updateValues);

Click here to learn more about Object.assign()

Answer №2

One way to update map2 with the key/value pairs from map1 is by using Object.assign(map2, map1).

Another option is to create a new object by combining the contents of both maps like so: map2 = {...map2, ...map1}, which will completely replace map2.

If you need a deep copy instead of just shallow copying, you can use JSON.parse(JSON.stringify(map2)) instead of simply assigning map2. If performance is a concern due to the size of the object, consider implementing a nested recursive copy method for deep copying!

Answer №3

To duplicate an object by looping through an array of keys, you can follow this approach:

let myMap1 = {};
let myMap2 = {};

myMap1["key1"] = "value1";
myMap1["key2"] = "value2";
myMap1["key3"] = "value3";

// create an array of the keys in myMap1
let myMap1_keys = Object.keys(myMap1);

// loop through the array of keys
for (let i = 0; i < myMap1_keys.length; i++) {
  myMap2[myMap1_keys[i]] = myMap1[myMap1_keys[i]];
}

It is recommended to avoid using a for..in loop for performance reasons and use a native for loop instead. You can read about the performance comparison here.

If you simply want to duplicate the object, you can achieve that with the following method:

let myMap2 = JSON.parse(JSON.stringify(myMap1));

Other methods like Object.assign() and ES6 spread operators will shallow copy the object, while the above method deep copies it, ensuring every level of the object is duplicated.

Answer №4

If you're looking to iterate over keys, this code snippet may be useful for you.

let fruits = {};
let colors = {};

fruits["apple"] = "red";
fruits["banana"] = "yellow";
fruits["orange"] = "orange";

var fruitKeys = Object.keys(fruits);

for (var j = 0; j < fruitKeys.length; j++) {
  colors[fruitKeys[j]] = fruits[fruitKeys[j]];
 alert(colors[fruitKeys[j]]);
}

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 proper way to add a string to a TypeScript array?

When attempting to add a string to a TypeScript array, I am encountering an error stating 'cannot push to undefined'. Is this the correct approach, or should I be using the spread operator instead? api.ts const api: IConfigName = {name: "getKey ...

Unable to bring in @material-ui/core/styles/MuiThemeProvider

I'm currently working on a React project that utilizes Material UI React components. My goal is to import MuiThemeProvider in src/index.js with the following code snippet: import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider"; . H ...

Secure JSON data by transmitting it safely to the front end within a Node.js environment

Currently, I am in the process of building an e-commerce application using NodeJs, Express, and MongoDB. The challenge I am facing is deciding how to securely pass JSON objects from the back end to the front end without compromising data security. Initiall ...

Passing an ID in Next.js without showing it in the URL

I am looking to transfer the product id from the category page to the product page without showing it in the URL Category.js <h2> <Link href={{ pathname: `/product/car/${title}`, query: { id: Item.id, }, }} as={`/p ...

Enable Sound when Hovering over Video in React Next.js

I am currently facing an issue while trying to incorporate a short video within my nextjs page using the HTML tag. The video starts off muted and I want it to play sound when hovered over. Despite my best efforts, I can't seem to get it working prope ...

Ways to access the values of checkboxes that are initially checked by default

Recently, I was working on a project that involved multiple checkboxes. My goal was to have the checkboxes pre-checked with values in the form (using reactive form). Users should be able to unselect the boxes as they wish and the data would be stored accor ...

unable to send array in cookie through express isn't functioning

Currently, I am in the midst of a project that requires me to provide the user with an array. To achieve this, I have been attempting to utilize the res.cookie() function. However, each time I try to pass an array as cookie data, the browser interprets it ...

Angular's use of ES6 generator functions allows for easier management of

Recently, I have integrated generators into my Angular project. Here is how I have implemented it so far: function loadPosts(skip) { return $rootScope.spawn(function *() { try { let promise = yield User.findAll(); $time ...

Disable the mouseenter event in jQuery when the window is resized

I am facing a challenge with my code. I have two different functions that are triggered based on the screen size - one for desktop and one for mobile. The issue arises when transitioning from a desktop to a mobile view, as the hover/mouseenter effect still ...

Ways to extract the first name and email address from a JSON payload

{ "userID": 1, "userHandle": "username", "first_name": "firstname", "last_name": "lname", "middle_initial": null, "email_address": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e203d250e29232f27 ...

"Encountering a bug with Angular-bootstrap pagination displaying an undefined function

Attempting to implement angular-bootstrap pagination footer Encountering an error TypeError: undefined is not a function at Object.fn (http://localhost:3000/lib/angular-bootstrap/ui-bootstrap-tpls.js:2265:5) at Scope.$get.Scope.$digest (http://l ...

Turn off email alerts for items and folders in ALFRESCO 5.2

Here's a snippet of JS code I created to toggle notifications with a button click: (Action.min.js): var me = this, jsNode = record.jsNode, content = jsNode.isContainer ? "folder" : "document"; if (jsNode.hasAspect("cm:emailed") ...

The art of revealing and concealing code blocks in AngularJS

I am currently working on a task in my AngularJS project. The requirement is that when both point directives within the md-autocomplete code are filled, the results directive should be displayed immediately without the need for any button. Additionally, if ...

Is it possible for me to alter the script for my button's onclick

Is there a way to replicate all properties of a div when creating a clone using JavaScript code? I have an existing script that successfully creates a clone of a div when a button is pressed, but it does not copy the CSS properties. How can I ensure that t ...

What steps are needed to switch colors after a loop has been clicked?

I have a loop setup like this: data: { show: false } .test { hight: 10px; background-color: red; } .test2 { hight: 15px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div v-for="value in da ...

Align images of varying sizes vertically within div containers, even when the image is larger than the div itself

I'm facing a challenge when it comes to aligning images vertically inside divs. The problem arises due to the following conditions: The images will have varying and unknown sizes. These images are larger than the divs they are contained in, requiri ...

Analyzing individuals within an array

Currently, I am faced with a particular challenge. In my dataset, there is an array of individuals where some names are duplicated but not identical due to slight variations. My task involves iterating through all the names to assess their similarity, fol ...

Adding HTML content inside an iFrame at a specific cursor position in Internet Explorer

Does anyone know a method to insert HTML into an iFrame specifically for IE? I have been using execCommand insertHtml in Chrome and Firefox, but it doesn't seem to work in IE. I was able to paste HTML into a content editable div using pasteHTML, howe ...

What is the best way to properly pass parameters?

const root = { user: (id) => { console.log("returning object " + JSON.stringify(id.id) + " " + JSON.stringify(storage.select("users", id.id))) return storage.select("users", id.id) } } Struggling to correctly pass the parameter ...

The functionality to disable the ES lint max length rule is malfunctioning

In trying to disable an eslint rule in a TypeScript file, I encountered an issue with a regular expression that exceeded 500 characters. As a result, an eslint warning was generated. To address this, I attempted to add an eslint comment before declaring th ...