Duplicate the array of objects and make alterations without affecting the original array

I have an array of objects that I need to deep copy and make modifications to each object without altering the original array or its contents. Here is my approach in JavaScript, but I am open to suggestions on a better method.

const users = 
[
    {
        id       : 1,    
        name     : 'Jack',
        approved : false
    },
    {
        id       : 2,    
        name     : 'Bill',
        approved : true
    },
    {
        id       : 3,    
        name     : 'Rick',
        approved : false
    },
    {
        id       : 4,    
        name     : 'Rick',
        approved : true
    }
];


const users2 = 
    users
        .map(
            (u) => 
            {
                return Object.assign({}, u);
            }
        )    
        .map(
            (u) => 
            {
                u.approved = true;
                return u;
            }
        );    


console.log('New users2 array of objects:')
console.log(users2);

console.log('The original users array remains untouched:')
console.log(users);

Output:

New users2 array of objects:
[ { id: 1, name: 'Jack', approved: true },
  { id: 2, name: 'Bill', approved: true },
  { id: 3, name: 'Rick', approved: true },
  { id: 4, name: 'Rick', approved: true } ]
The original users array remains untouched:
[ { id: 1, name: 'Jack', approved: false },
  { id: 2, name: 'Bill', approved: true },
  { id: 3, name: 'Rick', approved: false },
  { id: 4, name: 'Rick', approved: true } ]

Answer №1

One way to achieve this in a single pass is by utilizing Object.assign with the updated property.

const users = [{ id: 1, name: 'Jack', approved: false }, { id: 2, name: 'Bill', approved: true }, { id: 3, name: 'Rick', approved: false }, { id: 4, name: 'Rick', approved: true }];
const users2 = users.map(u => Object.assign({}, u, { approved: true }));

console.log(users2);
console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Alternatively, you can update using spread properties like so:

const users = [{ id: 1, name: 'Jack', approved: false }, { id: 2, name: 'Bill', approved: true }, { id: 3, name: 'Rick', approved: false }, { id: 4, name: 'Rick', approved: true }];
const users2 = users.map(u => ({ ...u, approved: true }));

console.log(users2);
console.log(users);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Absolutely, that approach seems efficient. Another suggestion could be implementing the modification during the cloning process to prevent iterating over the array multiple times.

const updatedUsers = users.map((user) => {
    const copiedUser = Object.assign({}, user);
    copiedUser.approved = true;
    return copiedUser;
}); 

Answer №3

My go-to method is using JSON.stringify and JSON.parse for deep copying arrays.

const people = [ { id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false },
{ id: 3, name: 'Charlie', active: true } ];

// Create a deep copy of the people array
const copiedPeople = JSON.parse(JSON.stringify(people));

Answer №4

If you need to copy an array in javascript, there are a few popular methods that can be used:

  • slice()
  • Array.from()

The slice method allows you to create a new array by extracting a portion or the entire content of an existing array based on specified begin and end indexes (both optional):

const a = [1,2,3,4,5,6,7,8,9]
/*
* Using only begin index
*/
const b = a.slice(2)
console.log(b) //Output: [3,4,5,6,7,8,9]
/*
* Using both begin and end indexes
*/
const c = a.slice(5,8)
console.log(c) //Output: [6,7,8]
/*
* No indexes provided
*/
const d = a.slice()
console.log(d) //Output: [1,2,3,4,5,6,7,8,9]

The Array.from() function is another useful method for creating a new array from array-like or iterable elements.

const a = Array.from('bar');
console.log(a) //Output: ["b","a","r"]
const b = ["for","bar"];
const c = Array.from(b);
console.log(c) //Output:  ["for","bar"]

Learn more about slice method

Explore Array.from() further

Answer №5

When working with React JS, I experimented with various methods to copy and make changes to a new array, but unfortunately, each attempt resulted in modifying the original array instead. Despite trying techniques such as using slice, Array.from, for loop, and the spread operator, the issue persisted.

The breakthrough came when I realized that I could resolve this by first stringify the original array and then storing it in a new variable. By subsequently parse the variable, I was able to obtain a fresh copy of the array without any reference complications, as advised by @Roman Yakoviv in a previous post.

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 is the best way to run a lengthy task in Node.js by periodically checking the database for updates?

In my current setup, there is a routine that continuously checks the database for any pending work orders. Upon finding one, it needs to execute it promptly. The system can handle only one work order at a time, and these tasks may vary in duration from 5 s ...

Gradient on multiple faces in Three.js

I'm currently struggling with creating an HSV cylinder using three.js. I am facing difficulties in properly mapping the gradient to the faces of the cylinder. Initially, I attempted to create my object in this manner: https://i.sstatic.net/WboAE.png ...

Automatically load content using AJAX when scrolling within a HTML5 segment

Recently, I've been developing a website that dynamically loads new content from a MySQL database as the user scrolls. However, I've encountered an issue where the new content is loaded even with minimal scrolling, rather than only when reaching ...

Encountered an error in AWS Lambda (Node 14.x): SyntaxError - Unexpected token 'export'

As I work on developing a straightforward login and registration system with AWS, I encountered an issue in AWS Lambda while testing my backend using Postman. The error code is detailed below: { "errorType": "Runtime.UserCodeSyntaxError& ...

What is the best way to create an `isHook` function in my code?

Is there a way to determine if a function passed is a React Hook? isHook(useState); // returns true isHook(() => {}); // returns false; I am looking for a method to distinguish whether a function attached to an object property is a hook or not. In cas ...

Data is not found in req.body when making a fetch request

I have been attempting to send a fetch request to my server, but I am consistently receiving an empty req.body. Here is the client-side script: const form = document.getElementById('form1') form.addEventListener('submit', (e) => ...

Is the iCheck feature designed to block all parent click events?

I've developed an "interaction tracker" system that collects anonymous data on clicked page elements. By implementing an event listener for clicks on the body, I can track interactions with any element on my site successfully. However, interestingly ...

Removing all Null Form Inputs from the Document Object Model upon Submission utilizing JavaScript

I am currently working on a conditional Shopify form that was passed down to me from another developer. The form utilizes JavaScript/Jquery for field validation, ensuring that all mandatory fields are completed before proceeding to the next step. After mak ...

HMR: The webpack-hot-middleware is not refreshing my webpage

My Vue application, titled hello-world, is utilizing webpack-dev-middleware and webpack-hot-middleware. When running the application, it shows that it's connected in the console. However, after making changes to my main.js file, the following message ...

Prevent postback when clicking on an image button in ASP

I have a project in ASP where I have an image button that allows users to browse an image and display it. I am utilizing a script for this project. Here is the code I am using: ASPX: <asp:Panel ID="stage" runat="server" cssClass="containment-wrapper" ...

Verify whether a specific value exists in my React array; if it does, display a specific component

I need to display different components based on the following criteria: Whether the items contain a specific value And if all 10 items have that value const DisplayComponents = ({ data }: Props) => { const filteredItems = data.items?.filter( ( ...

Sharing information between External JavaScript and React JS/Redux

Incorporating React-redux into an externalJs application (built on a custom JS framework) has posed a challenge for me. I am trying to initialize data for the Redux store from externalJS, but it seems that the external script is unable to access the React ...

Steps for including an animation class in a div

Is it possible to add the sweep to top blue color animation to the red box using a set-timeout function instead of hover? I tried using the following code but it doesn't seem to be working. Can you help me troubleshoot? setTimeout(function() { $( ...

Encountered an issue while trying to add images and text simultaneously in asp.net

I am trying to modify my code by adding an image along with the text. Here is the updated code: $(".ChatSend").click(function () { strChatText = $('.ChatText', $(this).parent()).val(); var recievertext= $('.ausern ...

Is it possible for Jquery to directly retrieve the form input without the need for a SET button in the script?

I have a script that functions as a basic countdown. All you need to do is enter a number, press the SET button, and click START for the countdown to begin. Although I primarily use this script in the gym, I often forget to hit the SET button after enteri ...

Utilize Object by referencing a string

I am trying to access an object from my node backend in React by using a string as a key. For example, if the string is 'Cat', I want to access the Cat object along with its corresponding key/value pairs. Here is an illustration of what the code ...

React displaying an error indicating that the setTimeout function is undefined?

While attempting to integrate the XTK library with React, I encountered an issue where it kept throwing an error stating that the setTimeout function is not a valid function. Surprisingly, my code appears to be flawless and works perfectly fine when used d ...

Tips for retrieving the HTML file of a modified canvas in HTML5

I’m currently working on a project to develop a website that allows users to design their own pages by simply dragging and dropping elements onto the canvas. The goal is for users to be able to save their creations as an HTML file. I’m facing challen ...

Issues with the visibility of React Bootstrap components

I'm troubleshooting an issue with the carousel on my website. When I try to load the page, the carousel appears blank. To set up the carousel, I used npm to install react-bootstrap. The carousel code can be found at . Upon checking the web console, ...

Is there a way to display points on each vertex of my geometry using React, three.js, and Three-React-fiber?

I'm trying to figure out how to utilize the pointsmaterial and points object within three-react-fiber. Currently, I have a custom geometry that I've imported from a .gltf file and I'm rendering it like this: <mesh castShadow recei ...