Ways to incorporate additional parameters into an object

Is there a way to incorporate new parameters into objects during a foreach loop in JavaScript?

const data = [big data];
data.forEach(async e => {
    Object.assign(e, {newData: 'string'};
    console.log(e); //new parameter added
})
console.log(data); //new parameter not added, why not?

During the forEach loop, I am trying to add a new parameter to each object. When I log the objects after using Object.assign, I can see that the new parameter has been successfully added. However, once the iteration is complete and I log my array of objects again, none of them seem to have the new parameter. Can anyone explain why this might be happening?

Answer №1

You made some mistakes in your code syntax such as missing commas and not using quotes around strings. Please see the solution below:

Update: If you want to add to an object, make sure to define the object (not a string) in an array.

const data = [{"big":true}, {"data":true}];
data.forEach(e => {
    Object.assign(e, {newData: 'string'});
    console.log(e); //added new parameter
});
console.log(data); //not added new parameter, why?

Update: You included "async" in your question within the forEach loop... Unfortunately, using async is not recommended for the forEach function. Instead, consider using the traditional for loop.

// Timeout
const timeout = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// Run in an async function!
(async () => {
  // Your array of objects
  const data = [{"big":true}, {"data":true}];
  // Loop
  for(let i = 0; i < data.length; i++) {
      const e = data[i];
      // Sleep for 1 second
      await timeout(1000);
      // Assign
      Object.assign(e, {newData: 'string'});
      // Debug
      console.log(e);
  }
  // The result will be displayed after all
  // awaits from the loop are completed
  console.log("result", data);
})();

Answer №2

Utilizing Object.assign() generates a newly created object.

In situations where you aim to produce an array of fresh objects, consider utilizing the map function.

const info = ["important", "details"];
let freshArray = info.map(element => {
    return Object.assign({}, {updatedData: element});
});
console.log(freshArray);

Note: the clarity of your inquiry is crucial. If you require just one object from the array:

let finalResult = {}
const info = ["important", "details"];
info.forEach(item => {
    finalResult[item] = 'information';
});
console.log(finalResult);

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

Discover how to generate nested dynamic routes in NextJS by linking to MongoDB data using the getStaticProps and getStaticPaths functions

Currently, I am facing a challenge with implementing dynamic paths in NextJS and I'm struggling to find a solution. Let me provide some context for better understanding. I am working on developing an ecommerce application using NextJS, and the folder ...

Showcase your skills in CSS, HTML, and Javascript

I attempted to search for something similar but came up empty-handed. I have two buttons. When I click one of them, I want to hide a certain division, but it's not working as expected. The divs d2 and d3 are initially hidden when the page opens, whic ...

I'm struggling to figure out the solution for this error message: "Unhandled Rejection (Type Error): Cannot read property 'filter' of undefined." Can someone please assist me with resolving this

Can you assist me? I am a beginner when it comes to javascript/React. I am currently following this tutorial https://github.com/Azure-Samples/js-e2e-client-cognitive-services and encountering the following error message: "Unhandled Rejection (TypeErro ...

Enhance your 3D models with react-three-fiber's canvas modification capabilities

I am looking to modify the model function within the canvas. Currently, I have two separate Models (functions in js files) named Model1 and Model2. Both Models have the ability to outline the mesh when hovered over. The existing code structure is as follow ...

Creating a responsive gallery using CSS techniques

I'm currently working on creating a simple gallery. My goal is to achieve the following design: https://i.sstatic.net/jq8pe.jpg However, the result I'm getting looks like this: https://i.sstatic.net/hSZyj.png The issue I'm facing is that ...

Attempting to use jQuery on click to set the background image of a div to a base64 encoded data image

Check out what I'm working on here The first div contains html with data:image;base64 <div id="large_photo_null" style="width:50px; height:50px; background-image: url( data:image;base64,R0lGODlhR.. );" > </div> When using html, the ba ...

Stagnant state persists despite attempted update

I am facing an issue with the useState component in my property management system. The state is not updating when loading the component. I expect the state of the item to change after receiving a response in the form stepper, but when adding a new dynamic ...

Adjust the text size for groupBy and option labels in Material UI Autocomplete without altering the size of the input field

Currently, I am utilizing Material-UI and ReactJS to implement grouped autocomplete functionality. See the code snippet below: import * as React from "react"; import TextField from "@mui/material/TextField"; import Autocomplete from &q ...

JavaScript does not support the enumeration of programs

I'm currently working on a program that takes user input (library, authorName) and displays the titles of books written by the author. Here is an example library structure: let library = [ { author: 'Bill Gates', title: 'The Road Ah ...

Combining php with jquery

This message contains a successful integration of PHP code within jQuery using the AJAX method. However, there are errors encountered which may be due to my lack of experience in jQuery. Uncaught ReferenceError: save_customer is not defined Uncaught Synt ...

Personal Information Management

After making a request for stormpath user custom data, I used the following code: res.render('home', { title: 'home', user: req.user.customData, }); Instead of receiving a JSON object of custom data as expected, a URL ('') ...

I have been attempting to implement validation in JQuery, but it doesn't seem to be functioning correctly

Can someone assist me with adding validation in jQuery? I'm stuck and need help solving this problem. $(function(){ $("#btn").click(function(){ var b=prompt("Enter your link"); $("a").attr("href",b); if($("b").v ...

Maximizing HTML5 Game Performance through requestAnimationFrame Refresh Rate

I am currently working on a HTML5 Canvas and JavaScript game. Initially, the frames per second (fps) are decent, but as the game progresses, the fps starts decreasing. It usually starts at around 45 fps and drops to only 5 fps. Here is my current game loo ...

Create a list using ng-repeat in AngularJS, each item separated by "custom categories"

I am looking to create a dynamic list that will display values entered by users, categorized by custom categories. The challenge is that I do not know in advance which category each element will belong to. Here's an example of how I envision the list ...

Utilizing AJAX to Access JSON Arrays

After clicking a button, I want to append specific parts of a JSON array (received from a server) to a table. However, I'm facing an issue where I am unable to add these parts to the table. Here is the JSON Array that was received from the server: {& ...

Create a React MUI component that allows menu items to become sticky when selected

Is there a way to make the mui MenuItem stay sticky to Select while scrolling down? To see the issue in action, check out this codesandbox example https://codesandbox.io/s/quirky-knuth-5hr2dg?file=/Demo.tsx Simply click on the select and start scrolling ...

Avoid having gulp's uglify plugin remove es6 code

I've encountered an issue while using gulp babel to compile es6. It seems that uglify is stripping out my es6 code completely. Strangely, I'm not receiving any errors in my command line during the process. Have you faced this problem before? Any ...

Challenges with declarations and operators

Hi everyone, I'm trying to tweak the order of operators in a code snippet so that the result logged is 0. Can someone help me figure this out? numbers = [23, 12, 71, 10] operators = [ (a, b) => a + b, (a, b) => a / b, (a, b) => a * b, (a, b) ...

Utilizing Eval for streaming a flash video

Currently attempting to utilize Eval in order to play a flv file from a database that is stored in a table. There could potentially be multiple videos, so my approach is to list them out and define their paths accordingly. <ItemTemplate> ...

While attempting an AJAX request with jQuery, I encountered the following error message: "Error: ER_SP_UNDECLARED_VAR: Undeclared variable: NaN"

I encountered an issue that says: ` throw err; // Rethrow non-MySQL errors ^ Error: ER_SP_UNDECLARED_VAR: Undeclared variable: NaN ` while attempting a jQuery AJAX get request, and I'm unsure of the cause. My backend is built using node.js a ...