Transfer elements between arrays by maintaining the original reference

Looking for help with updating the indices of array1 in this scenario. Any suggestions on how to make the indices of array2 reference the indices of array1?

http://jsfiddle.net/y8rs56r3/

    var array1 = [
        {num:"one"},
        {num:"two"},    
        {num:"three"}
    ];
    var array2 = [];
    var i = array1.length;
    while(i--){
        if(i!=1)array2.push(array1[i]);
    }

    array2[0].num = "one updated";
    console.log(array2);
    console.log(array1);

The issue here is that array1[0] remains unchanged.

Answer №1

To transform your array of objects, follow this example:

var originalArray = [
  {number:"one"},
  {number:"two"},    
  {number:"three"}
];

var updatedArray = [];
for(item in originalArray){
  updatedArray.push(originalArray[item]);
}

updatedArray[0].number = "one modified";
console.log(updatedArray); // Output: [Object { number="one modified"}, Object { number="two"}, Object { number="three"}]
console.log(originalArray); // Output: [Object { number="one modified"}, Object { number="two"}, Object { number="three"}]

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

Which option's value was recently removed from the fetch command?

I created a function to handle duplicate selections in a select element. It is functioning properly, but I noticed that when I remove an option from the select, my array remains unchanged. If I remove an option, I want my code to detect the value of that ...

JavaScript can be used to track the number of elements added to an input box by detecting when a key is pressed, but not yet released

How can I use JavaScript or Angular to count the number of characters entered in an input box when a key, like 'a', is pressed but not released on the keyboard? <input type="text" name="charactercount" value="aaaaaa&qu ...

Merging various variables together where applicable in JavaScript

I am looking to combine different variables if they exist and return the result. However, I need to separate the values with "-" and only return the variables with a value. Here is my code: var test = ""; var test1 = ""; var test2 = ""; var test3 = ""; ...

Is there a way to dynamically load a JSON configuration during runtime within a React application?

I am working on a React app that includes static content and does not use Node.js. I am in need of loading a configuration file in JSON format during runtime. The configuration file must be loaded in runtime because it needs to contain different data depe ...

Incorrectly combining strings with strcat function

I am currently working on a program that reads strings from a file, stores them in a 'string buffer', and then concatenates those strings before writing them to another file. #define _CRT_SECURE_NO_WARNINGS #include <cstdlib> #include < ...

Is it possible to adjust the range of a range slider based on the selection of a radio button or other input method?

I have a query and I’m hopeful you can assist: function UpdateTemperature() { var selectedGrade = $( "input[name='radios']:checked" ).val(); $( ".c_f" ).text(selectedGrade); var value1 = $("#tempMin").val(); var value2 = $("#tempM ...

In an MVC 4 application, when using JQuery to replace HTML and then calling the .show() function, the

I have a null div element: <div id="reportBody"></div> with basic styling: #reportBody { height: 100%; } The reportBody div is located within a hidden modal that is triggered by a button click. I am using jQuery and AJAX to call a contro ...

Next.js fails to refresh the content upon initial view

Snippet from my index.js file: import Post from "@/components/Post" import Modal from "@/components/Modal" import {useState} from "react" export default function Home() { // Setting up states const [modalTitle, setModalTitle] = useState('Title&a ...

Can the page's user interface stay the same even after refreshing the page?

Are you considering including a test case to verify if all checkboxes are unchecked after the page reloads? Is it possible for checked checkboxes to remain selected even after reloading or navigating away and returning to the page? Could this issue be due ...

Utilize jQuery to locate and add items that match specific data attributes to corresponding ID elements

In my HTML code, I have a group of spans within a div that I am attempting to match and relocate to a corresponding id. Each span contains a data attribute that corresponds to the parent ID of the target element. My goal is to utilize jQuery to find the ma ...

Should we designate the array index as the unique identifier for React components?

I have an array filled with different strings that I need to map through and display in a React component. React raises concerns when encountering identical strings within the array. My query is this: Can I assign the position of each element in the array ...

Issue in Vue: When using v-model on fields within a nested array, instead of mutating the existing value, a

Just starting out with Vue (+ Vuex) and I've been working on a project to help me learn the ropes. It's been about a week now, and things are starting to come together nicely, but I've hit a bump in the road that's got me scratching my ...

Print the value of an array element following a while loop in PHP

Is there a way I can display the value after the while loop ends without encountering an Undefined index error? $sql_cast = "SELECT * FROM title_cast INNER JOIN title ON (title_cast.id_title = title.id) ...

Choosing items in select2 ahead of time using JSON

Is there a way to preselect an option in select2 when using disabled: true and locked: true options? I am retrieving JSON data for a text field and would like to have an option preselected. Does something like this exist? { id: 0, text: 'story' ...

Designing Interactive Circular Dates on Website

Currently, I am working on a webpage using HTML, CSS, JavaScript, and PHP. The goal is to design a page that features 7 circles representing the current date and the next 6 days. Users should be able to click an arrow to navigate to the following 7 days. ...

A guide on incorporating multiple nested loops within a single table using Vue.js

Is it possible to loop through a multi-nested object collection while still displaying it in the same table? <table v-for="d in transaction.documents"> <tbody> <tr> <th>Document ID:</th> &l ...

Utilizing Smarty to Retrieve JavaScript Variables from Database Entries

Currently, I am working on a PrestaShop page that uses the file extension ".tpl". To enable auto complete for the javascript code, I have defined an array of currencies as shown below: var currencies = [ { value: 'Afghan afghani', data: 'AF ...

Adding a list without a specific order into a paragraph with the help of jQuery

Working on a client-side class, I am in the process of changing an XHR request and getElementById function to a jQuery ajax request along with jQuery document manipulation. The task at hand is to display descriptions of items available from "Rob's Roc ...

Trigger keydown and click events to dynamically update images in Internet Explorer 7

There is a next button and an input field where users can enter the page number to jump to a specific page. Each page is represented by an image, like: <img src="http://someurl.com/1_1.emf" > // first page <img src="http://someurl.com/2_1.emf" ...

No location matched any routes

I'm currently working on a notes application, and I've encountered an error when trying to edit the notes. The error message says "No routes matched location id ...". Any idea what could be causing this issue? The approach I'm taking is to ...