Generating a fresh object derived from an existing object without saving any modifications

I am facing an issue with using an Array to store boilerplate objects that can be copied, modified, and added to another Array. The problem arises when the new Array takes ownership of the object, causing changes to persist in the original object.

For example:

var originals = [{ name: "One", value: 1 }, { name: "Two", value: 2 }, { name: "Three", value: 3 }];

var notOriginal = [];

notOriginal.push(originals[0]);

// This results in - notOriginal = [{ name: "One", value: 1 }];

notOriginal[0].name = "Uno";

// As a result - originals = [{ name: "Uno", value: 1 },...];

I want to ensure that the "originals" variable remains unchanged throughout this process.

Although I have searched extensively online and tried various solutions, I am still struggling to find a proper fix for this issue.

This behavior is particularly noticeable in VueJS when dealing with object manipulation within my data().

Answer №1

Create a duplicate of the data by utilizing JSON.parse & JSON.stringify

var originals = [{
  name: "One",
  value: 1
}, {
  name: "Two",
  value: 2
}, {
  name: "Three",
  value: 3
}];

var notOriginal = [];

notOriginal.push(JSON.parse(JSON.stringify(originals[0])));



notOriginal[0].name = "Uno";
console.log(originals)

Answer №2

One way to duplicate an object is by using the Object.assign method.

let initialObjects = [{
  title: "Apple",
  quantity: 5
}, {
  title: "Banana",
  quantity: 7
}, {
  title: "Orange",
  quantity: 3
}];

let copiedObjects = [];

copiedObjects.push(Object.assign({}, initialObjects[0]));

copiedObjects[0].title = "Pear";

console.log(initialObjects);

Answer №3

Objects are passed by reference.

To create a copy of an object, you can use the Object.assign({}, obj) method. This will produce a new object with all properties duplicated from the original.

var originals = [{ name: "One", value: 1 }, { name: "Two", value: 2 }, { name: "Three", value: 3 }];

var notOriginal = originals.map(obj => Object.assign({}, obj));

notOriginal[0].name = "bart";
console.log(originals[0], notOriginal[0]);

Answer №4

After experimenting with jQuery.extend(true, {}, myObj), I was able to find a resolution. However, I am interested in learning the specific term for this process to deepen my understanding of reactivity.

Appreciate any insights on this topic. Thank you!

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

Best practices for effectively implementing Vuex getters within the Nuxt Vue Composition API

I have been using @nuxtjs/composition-api(0.15.1), but I encountered some issues when trying to access Vuex getters within computed(). Below is the code snippet using composition API: import { computed, useContext, useFetch, reactive } from '@nuxtjs/ ...

What is the process for deleting an animation using JavaScript, and how can the background color be altered?

Two issues are currently troubling me. First off, I am facing a challenge with an animation feature that I need to modify within the "popup" class for a gallery section on a website. Currently, when users load the page, a square image and background start ...

serializeArray encounters difficulty in locating certain input elements

I've created this HTML layout: <div class="col-md-12"> <div class="form-group"> <label>Mini description (displaying the latest added destinations and meta description)</label> <textarea class="for ...

How to display an HTML element conditionally with v-if based on a variable's value

Looking for a way to display a <div> element, including nested <div>s, based on the value of a variable. I'm currently using v-if, but open to better suggestions. I attempted wrapping the entire <div> in a <template v-if> as s ...

The JavaScript class failed to work properly within the asp.net framework

I have successfully implemented a JavaScript function on my aspx page. Here is the code snippet: <script type="text/javascript"> $(document).ready(function () { console.log("ready!"); var options = []; var ...

There are a total of 152 issues found in the index.tsx file within the react

Despite everything working correctly, I am continuously encountering these errors. Is this a common occurrence? What steps can I take to resolve them? I have developed my react application using Javascript instead of Typescript; however, I don't belie ...

What is required to run npm rebuild node-sass --force following each instance of a `yarn add` command?

As I attempt to set up the isemail npm library, everything appears to be going smoothly. However, when I execute yarn start:dev, which essentially runs "npm run build:dev && ./scripts/gendevconfig.sh && cross-env BABEL_DISABLE_CACHE=1 NODE_ ...

Best Practices for Handling an Abundance of Data in React or Java

I am facing a challenge with my project setup, where I have the front end in ReactJS and the backend API in Spring Boot. The task at hand is to display a drop down list filled with records retrieved from the API. Here's the scenario: I receive a list ...

Methods for setting the value of a scope variable within a controller's function

I have a goal of presenting a page that calculates a balance in the background and displays it. To achieve this, I decided to separate the balance into its own directive. Here is the directive I have created: app.directive('smBalanceInfo', fun ...

How can I incorporate the 'client' application into the 'loading.js' file?

I implemented a Lottie component in my loading.js file. Utilizing the App router (Next13). This is the code for the lottie component: import { Player } from '@lottiefiles/react-lottie-player'; import LoadingLottie from '@/assets/loading.j ...

What is the best way to synchronize CouchDB with multiple PouchDB instances in an AngularJS application?

I need help with my Angular project. I'm trying to figure out how to sync multiple PouchDB databases to a single CouchDB instance without losing any data. Can anyone provide some guidance or advice? ...

What is the best way to send props to a component that is exported using a Store Provider?

I'm trying to export my react component along with the redux store Provider. In order to achieve this, I've wrapped the component with an exportWithState callback. However, I'm facing an issue where I can't seem to access the props that ...

Validation of forms - Must include one particular word from a given set

I am in the process of utilizing Javascript to validate an input field with the specific formatting requirements outlined below: "WORD1,WORD2" The input must contain a comma separating two words, without any spaces. The first word (WORD1) can be any word ...

Assign the default value of a Vue prop to the options of its parent component

I have a child component that needs to accept a value given in the component's parent's $options object as a possible default value. In the background, the component should be able to receive its data through a prop or from a configuration. Howe ...

Have you ever wondered why the expression `Number(new Boolean(false))` always returns `0

In the case of Boolean(new Boolean(...)) === true, it is because new Boolean(...) is treated as an object. However, why does Number(new Boolean(false)) === 0 (+new Boolean(false) === 0) and Number(new Boolean(true)) === 1? Instead of resulting in NaN. Wh ...

The style of the button label does not persist when onChange occurs

Encountered an interesting issue here. There is a button designed for selection purposes, similar to a select item. Here's the code snippet: <button class="btn btn-primary dropdown-toggle" style="width: 166%;" type="button" id="dropdownMe ...

What is the best way to send a function along with personalized data?

Currently, I am working on a project using node.js with socket.io. I am looking for a way to have socket.on() use a unique callback function for each client that joins the server. Here is my current technique: I have created a simple JavaScript class whi ...

Exploring the combination of AWS Amplify with Vue Router's history mode

My Vue app utilizes Vue router and I have been tasked with creating a website for a client. One specific part of the site is meant to be "secret" and should only be accessible through a direct link. In simple terms, I want users to reach myamplifyapp.com/ ...

having difficulty sending the username and password from the HTML page to the controller in AngularJS

In my AngularJS controller, I am having trouble retrieving the values of the username and password fields after submitting the login form. Here is the HTML code for the form: <form class="form-signin" action="" method="post"> ...

Automatically choose radio buttons within an li element in a loop

Hey there, I'm new to SO and this is my first question. As a bit of a newbie, I found this jquery code snippet on another SO answer that I want to use. The function I'm aiming for is the same, but the markup structure in my HTML is different bec ...