Attempted to iterate over an array with the intention of appending an extra key value pair, but ended up only retaining the final value

While attempting to create a new array of objects from an existing array that I am iterating through, I seem to only retain the last value. I understand why this is happening, but I am unsure of the best approach to achieve the desired outcome.

var existingThing = ["one","two","three"];

var thingtoAdd = {};

var newthing = [];

for (var i = 0; i < existingThing.length; i++) {

    thingtoAdd.key = existingThing[i];
    thingtoAdd.value = existingThing[i];
    thingtoAdd.selected = "true";
    newthing.push(thingtoAdd);
}

console.log(JSON.stringify(newthing));

The resulting output is:

[{"key":"three","value":"three","selected":"true"},
{"key":"three","value":"three","selected":"true"},
{"key":"three","value":"three","selected":"true"}]

Answer №1

Revise your script to:

let existingItems = ["red","blue","green"];

let newItems = [];

for (let i = 0; i < existingItems.length; i++) {

    let itemToAdd = {};

    itemToAdd.key = existingItems[i];
    itemToAdd.value = existingItems[i];
    itemToAdd.selected = "true";
    newItems.push(itemToAdd);
}

console.log(JSON.stringify(newItems));

You are updating the same object itemToAdd repeatedly because it's defined in the outer loop scope. By placing it inside the inner loop block, a new object is created during each iteration with the appropriate values.

Answer №2

Make sure to clear out the object called thingToAdd after adding it to the new array

for (var i = 0; i < existingThing.length; i++) {

    thingtoAdd.key = existingThing[i];
    thingtoAdd.value = existingThing[i];
    thingtoAdd.selected = "true";
    newthing.push(thingtoAdd);
    thingToAdd = {};
}

Answer №3

Whenever you add an object to the array newthing by pushing it, you're actually only adding a reference to that object, "thingtoAdd". This means that when you update the object in later iterations of your for loop, you're directly updating the original object. As a result, the array contains multiple references to the same object, leading to duplicates or all objects having the last updated value.

To create new instances of the object each time, you need to empty the object. If you place a debugger inside the for loop and inspect the "newthing" array, you will see this behavior.

var obj = { val: 5 }
function increment(obj) {
    obj.val++
}
increment(obj)

When you run the above function, the value of obj will be incremented with each call.

function increment(val) {
   val++
}
val = 5
increment(val)
alert(val)

In contrast, in the second example, the variable val remains unchanged. This difference lies in the fact that in the first case, the object referenced by obj is modified, while in the second case, only the variable val is changed.

Answer №4

    let currentItems = ["apple","banana","orange"];

let newItems = [];

for (let i = 0; i < currentItems.length; i++) {
    let itemToAdd = {};
    itemToAdd.key = currentItems[i];
    itemToAdd.value = currentItems[i];
    itemToAdd.selected = "true";
    newItems.push(itemToAdd);
}

console.log(JSON.stringify(newItems));

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

PHP array_merge replaces its original content

Having difficulty with the array_merge function to construct an array of items. The current code being used is as follows: $items = []; foreach ($products as $product) { Log::info($product->orderproduct->idorder_product); $items = array_me ...

The git clone operation encounters a problem with the error message: unable to connect, connection refused on localhost port 80

Currently for my project, I'm utilizing isomorphic-git. However, when I try to implement the git.clone function, I encounter the error message Error: connect ECONNREFUSED 127.0.0.1:80. To provide an example of what I am attempting to achieve: import ...

I'm looking for a way to have an element shift in a particular direction only when two keys are pressed simultaneously

Having trouble moving a square diagonally when two keys are pressed simultaneously. Trying to create an if statement that detects both key presses at the same time and triggers the movement. However, all attempts have failed so far, leaving uncertainty abo ...

Is there a radio button that can dynamically update and modify the current view?

Although I don't consider my issue to be overly complex, as a newcomer I am struggling to find a straightforward solution. The form I have collects various items and on the output page generates a table based on this data. For instance, one question ...

Select a user at random from the reactions in the message

Is there a way to select a user at random from message reactions on Discord? Despite going through all the documentation, I'm still unsure about how to do this. ...

"Redirecting visitors based on their location using GeoIP targeting for

Is there a way to implement a code that redirects users based on their location? For example, if a user accesses the site from the United Kingdom, they should be redirected to /UK/, if from the US to /US/, and if from anywhere in the EU (excluding the UK) ...

Utilize JavaScript to randomly choose images as background tiles in HTML

Currently, I am in the process of developing a game using HTML/CSS/JavaScript. My background is currently set to a single image (100px / 100px) being repeated vertically and horizontally to tile across the entire page body; CSS: body { background-ima ...

To combine both jquery-1.min.js and jquery.min.js is essential for achieving optimal functionality

When using these two files, only one of them can work on a page. <script src="jquery.min.js"></script> <script src="jquery-1.min.js"></script>//Only the second one works Alternatively, if the order is changed: <script src="jq ...

Having trouble setting up Node.js on a Mac computer

Upon completing the regular installation on Mac, I am unable to find Node in the terminal. Even after defining the PATH with the line: export PATH=/usr/local/bin: $PATH, it still does not locate Node or npm in the terminal. ...

Issue with Angular routing not functioning properly post form submission

Recently, I created a contact form using Angular for the frontend and NodeJs with Nodemailer for the backend. However, I encountered an issue where after submitting the form, instead of redirecting to the default page set in the app, the page remains on th ...

Spin a Collada model on its y-axis

I am struggling with a three.js scene that features a 3D Homer Simpson standing on a plane. My goal is to rotate him around his y-axis using the mouse. The code I have put together is almost there, with pieces borrowed from various sources. However, I am ...

Struggling with passing data to a child component in React

I am currently working on a gallery project where users can click on an image to view it in a separate component using props. The images are sourced from a hardcoded array, and the challenge lies in connecting this data to the component accurately. I have ...

Trouble with unproductive downtime in ReactJS and JavaScript

I'm looking for a way to detect idle time and display a dialog automatically after a certain period of inactivity. The dialog should prompt the user to click a button to keep their session active. Currently, when the user clicks the button it doesn&a ...

Execute an asynchronous request using Javascript to communicate with a Spring Controller

I've created a JSP page that includes some JavaScript code: function sendData(tableID) { var table = document.getElementById(tableID); var dataArray= new Array(); for (var i = 1;i<table.rows.length; i++){ var row = table. ...

Obtain the values from controls within the <td> element

I'm experiencing some difficulty creating an array of table cell values because the cells contain controls, not just plain text. $("#tbl_CGT tr").each(function() { var arrayOfThisRow = []; var tableData = $(this).find('td'); if (tab ...

Manipulating the content of a specific row's table cells with a text box in jQuery Datatables

I am working with a jQuery datatable that consists of only one column. Every time a row is selected, a panel opens with a text box that automatically populates with the name of the selected td. I am trying to figure out how to edit the name of the selected ...

The requested page for angular-in-memory-web-api could not be located within the Angular 4.2.2 CLI web-api functionality

Currently, I am delving into the Angular framework (specifically version 4.2.2) and going through the Tour of Heroes tutorial. As I progressed to the HTTP section, the tutorial introduced the use of angular-in-memory-web-api to simulate a web api server. ...

NodeJs: Transforming strings into UUID v4 efficiently

Suppose I have the following string: const input = '83e54feeeb444c7484b3c7a81b5ba2fd'; I want to transform it into a UUID v4 format as shown below: 83e54fee-eb44-4c74-84b3-c7a81b5ba2fd My current approach involves using a custom function: funct ...

Is there a method for the parent to detect changes in its output when passing around complex objects to its child?

I am facing a challenge with a complex object that is being passed down from a parent component to its child components. The child components further break down this object and pass parts of it to their own children, creating layers of complexity. At times ...

Cyclic Character Array Buffer - C

I've encountered a issue while using a circular char * array as a buffer to transfer data from multiple mapping threads to a reducing thread. My problem arises when the array runs out of space, causing segmentation faults. How can I resolve this issue ...