manipulating data using javascript

I have an array of objects like this:

var arr = [{'name':'one','age':24},{'name':'two','age':21}]

Then I assigned this array to another variable var newVar = arr. Next, I modified the value of an object in newVar using newVar[0].age = 18. However, this change also affected the original data stored in arr. The updated array became:

var arr = [{'name':'one','age':18},{'name':'two','age':21}]

I would like the original data to remain unchanged when modifying values in a different variable that holds the same data. How can I achieve this in JavaScript?

Answer №1

Javascript manages objects by reference. If you need to modify the value within an object, it is recommended to create a duplicate of it. This will result in two distinct objects.

Here's how you can clone an object:

Discover the most efficient method for deep cloning an object in JavaScript.

Answer №2

Make use of the new Array() method.

let array = [{'name':'John','age':30},{'name':'Jane','age':25}];
    let newArray = new Array(array);

Answer №3

When it comes to copying an array, the slice method is typically used. However, it's important to note that slice only creates a shallow copy. For a deep clone, the combination of the map method and $.extend can be utilized to clone an object:

var arr = [{'name':'one','age':24},{'name':'two','age':21}]
var newArr = arr.map(function(el) {
    return $.extend({}, el);
});

newArr[0].name = 'TEST'
console.log(newArr[0].name, arr[0].name); // TEST one 

An alternative method involves some JavaScript magic for a shorter implementation:

var newArr = arr.map($.extend.bind(null, {}));

The end result remains unchanged.

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 are the steps to create a project template in WebStorm by saving an existing project?

Currently, I am working on my Express.js project in WebStorm 8 and I would like to save it as a project template. Can you please guide me on how to do this using WebStorm? ...

Heroku-hosted application experiencing issues with loading website content

I have been working on a nodejs application that serves a web page using express and also functions as a discord bot. The app runs smoothly on localhost with both the web page and discord functionalities working correctly. However, when I deploy it to Hero ...

Issue with clicking and toggling classes in Javascript

I am experimenting with creating a simple 3 slide slider, but I am facing some issues with the JavaScript. My goal is to have the current slider slide out and the selected one slide in when clicking on the slider color. I'm attempting to achieve this ...

Mysterious python eccentricity requiring clarification

I am intrigued by a peculiar behavior in Python that I am trying to comprehend. While it doesn't seem like a bug, the reason behind this behavior eludes me. My goal is to load a group of images into a list and then manipulate them. Let's take a ...

Exploring Angular 11 Testing: Troubleshooting Async Issues in Jest with RxJS Timer

I encountered an issue while working on a test where I received the following error message: "Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5 ...

Adding items to an array within a jQuery each loop and performing a jQuery ajax request

I am trying to loop through an array, push the results into a JavaScript array, and then access the data outside of each loop and AJAX call. Can anyone explain how to do this? This is what I have attempted: var ides = ["2254365", "2255017", "2254288", ...

Explore the HTML code of a webpage to locate a specific attribute, and then identify the parent div element associated with that attribute

Is there a way to identify the parent div ID in javascript or jquery by searching HTML src for a specific attribute or text? Consider the following code snippet: <div id="ad_creative_1" class="ad-div mastad" style="z-index: 1;"> <script>(func ...

Is there a way to verify the location of an element?

Currently, I am attempting to monitor the position of the 'car'. When the car reaches a top offset of 200px, I would like to apply a specific property to the 'phone' element. The concept is that as you scroll down, the car will move, an ...

For every iteration, verify the presence of the image

I am currently working on a foreach loop to iterate over the data returned by an ajax call. Within this loop, I am checking if each record has an associated image. Code for Checking Image Existence: function checkImageExists(url, callback) { var img ...

The utilization of the 'this' keyword within an object is not feasible due to its placement within a separate function

The issue I am facing is while using vue.js, but I believe it might also be applicable in plain JS. The problem arises when I am inside a function that is within another function; I have to reference variables by their full path such as Object.variable i ...

Utilizing BEM Class Names in React

How can I utilize the Post component in a way that assigns unique classes to new and old posts following BEM recommendations? Assign a unique className to every element Avoid cascading dependencies like (.posts-new post or .posts-old post) Each component ...

The display of data attributes is not being rendered correctly

Check out the fiddle I'm currently working on: http://jsfiddle.net/7Z8wY/9/ The HTML section looks like this: <div class="container"> <div class="right"> <div id="cityList" class="inner-table"></div> </div> ...

Elements powered by jQuery failing to load upon dynamic webpage(s) loading via ajax

Dynamic loading of jQuery elements, such as Ibuttons, seems to be causing issues when implemented with an ajax dynamic content loader. The entirety of my website is rendered through Ajax just like this: <html> <header> {jQuery} </header> ...

React App stalled due to continuously running function

In this section of my React app, the createBubbles function is functioning properly. However, I am encountering an issue where the entire app freezes when navigating to another page after visiting this one. The console displays the following errors and de ...

Is there a way to use JQuery to determine which button in a table was clicked and retrieve all the data from that specific row?

Below is the HTML code: <table class="table table-stripped table-bordered table-hover centerAll" cellpadding="10"> <thead> <th>Nombre</th> <th>Descripci ...

Ways to retrieve the identifier of a specific element within an array

After successfully retrieving an array of items from my database using PHP as the backend language, I managed to display them correctly in my Ionic view. However, when I attempted to log the id of each item in order to use it for other tasks, it consistent ...

Exploring the initial output in JavaScript

I'm attempting to include the following body in JSON format. However, it seems that only one value is being added. json = { "Myname":"Nate", } Here is the code I'm trying to add: Body = Myproperty: [{ "vehicle": "car", "color": "Red" }, { ...

The file type input is not directing to the correct folder in Internet Explorer version 9

Could someone please assist me with this problem in IE9? After I select a file to upload, then choose another one, it shows "fakepath" in IE9. See the image below for more information: https://i.sstatic.net/QsJFk.png https://i.sstatic.net/3nWRC.png htt ...

Tips for Transferring Values Between Multiple Dropdown Menus with jQuery

Hello there, can anyone guide me on how to transfer selected items from one multiple combo box to another multi-combo box? I would really appreciate it if someone could provide an example for this scenario. <HTML> <HEAD> <TITLE></T ...

Creating Unique Designs with Multiple Shapes and Elements using Clipping Masks

I have a design piece to create that I initially built using three separate square div containers with independent background images. However, this method feels rigid to me as it requires chopping up and restaging a new image each time it needs to be chang ...