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

The module cannot be located, despite my efforts to reinstall and verify all addresses, the error still persists

Error in showStudent component: Module not located: Unable to resolve '@material-ui/data-grid' in 'C:\Users\USER\Desktop\Database\client\src\components\showStudent' The code in the showstudent ...

Is it possible to include numbers and commas in JQuery Validation?

I have implemented a jQuery validation plugin to validate the fields of a form. One specific requirement is to validate a field to only allow commas and numbers. Below is the HTML code snippet: <input type="text" placeholder="Number of Employees" requ ...

When loading a page for the first time, the Vue.js transition does not take effect

After setting up a navbar that switches between two components, I encountered an issue with the fade-in animation not running when the page is first opened. The animation only works when using the navbar links to switch components. Any suggestions on how t ...

Search functionality that dynamically updates results as the user types, thanks

I am currently working on implementing a search feature that can assist users when typing in their search queries. The goal is to use Ajax to dynamically show results as the user types. Currently, the functionality requires the user to hit the search butt ...

Ways to determine the total amount of existing files in a directory

For the purpose of file management and moving files to another folder, I am attempting to determine the count of files that already exist in a specified folder. foreach($checkboxfiles as $checkboxfile) { $src_file = $checkboxfile; $fileName = bas ...

Several features - Second function malfunctioning

The initial inquiry is effective. However, the subsequent one is encountering issues as it is failing to confirm if an email contains the "@" symbol. My attempted solution involved reordering the functions related to email validation. <body onload="ch ...

Flexbox Resizing Notification(?)

Recently, I've been utilizing flexbox in my layout design and it has been a game-changer. However, I am facing an issue that might be linked to my heavy use of AngularJS, particularly the ng-include feature. The specific problem arises when I incorpo ...

Storing Form Input in Browser's Local Memory

I am currently working on a form section where individuals can input their email addresses. However, I have encountered a couple of issues: (1) After submitting an email address, the page refreshes. While I understand that this is inevitable without usin ...

Organize a collection of items in AngularJS

Consider the following array: var members = [ {name: "john", team: 1}, {name: "kevin", team: 1}, {name: "rob", team: 2}, {name: "matt", team: 2}, {name: "clint", team: 3}, {name: "will", team: 3} ]; I want to create an unordered list for each ...

How to retrieve the length of an array stored in the data object of a Vue instance

Having trouble retrieving the length of an array in vue. The array is located in the data object like so: data() { return { slides: [ { image: require("@/assets/img/carousel/couple.jpg"), caption: "A coupl ...

What is the best approach for presenting MySQL data on an HTML div through Node.js?

When working with Node.js, I prefer using Express as my framework. Here is the AJAX code I have on my member.ejs page: function load_member(){ $.ajax({ url: '/load_member', success: function(r){ console.lo ...

Utilizing Ember to transmit models to Bootstrap Popovers

Seeking assistance from anyone familiar with utilizing Bootstrap for Ember components to help resolve an issue. I am trying to understand how to pass a model to the component when using {{bs-bind-popover}} <div {{bs-bind-popover templPop}}>Show pop ...

top margin is functioning properly in Internet Explorer, but not in Google Chrome

margin-top is behaving differently in IE compared to Google Chrome. Two menus are supposed to be displayed one above the other in my design. The issue lies in the line margin-top:30%; within .anothermenu ul. In Chrome, the second menu appears above the f ...

Unexpected TypeError occurred when trying to Fetch data from an Express Server hosted on Window object

Error Message : Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Invalid name Feeling stuck as I looked around, unsure of what's causing this issue. My goal is to develop a website that can eventually make a ...

Please explain this ES6 syntax to me: Using a colon after a function call

While exploring the documentation for a flux store in React, I came across an example that caught my attention. import {ReduceStore} from 'flux/utils'; class CounterStore extends ReduceStore<number> { getInitialState(): number { ret ...

What is the best way to replicate the content of the textarea exactly as it is (with all line breaks and special characters)?

Below is the Laravel form I have, and I need to extract the text in a way that retains its original format: <style type="text/css" media="screen"> #editor { position: absolute; top: 150px; right: 150px; bottom: 15 ...

Is the latest Swiper JS version compatible with outdated web browsers?

Seeking information on browser compatibility. I am interested in upgrading to the latest version 8.4.5 of Swiper JS for my project, currently using version 4.1.6. Upon examining their shared Github repository file .browserslistrc, I noticed changes that ta ...

The revalidation feature in Next.js' getStaticProps function does not seem to be

https://i.stack.imgur.com/vnNMQ.png I have a question regarding my use of the getStaticProps function in index.js. I am trying to ensure that my API call runs every 60 seconds when a user visits my page, but I am experiencing issues with revalidate not wo ...

Can javascript be used to swap out the folder in my URL?

I have been searching for solutions on how to change the language of my website using jQuery, but so far I have not found anything that works for me. Let's take my website as an example: www.domain.com I have separate folders for different languages. ...

When organizing data, the key value pair automatically sorts information according to the specified key

I have created a key value pair in Angular. The key represents the questionId and the value is the baseQuestion. The baseQuestion value may be null. One issue I am facing is that after insertion, the key value pairs are automatically sorted in ascending ...