When duplicating a data object in Vue.js and removing a property, the original object will also have that property removed

My data object in Vue is structured as follows:

rows[
0 {
  title: "my title",
  post: "my post text",
  public: false,
  info: "some info"
},
1 {
 title: "my title",
  post: "my post text"
  public: true,
  info: "some info"
},
2 {
 title: "my title",
  post: "my post text"
  public: false,
  info: "some info"
}
]

To prepare this object before sending it to the backend, I make a copy and remove certain properties if necessary using the following method:

var postData = this.rows;
      postData.forEach(function(o) {

        if (o.public === true) {
          delete o.info;
        }
      });

      var uploadData = {};
      uploadData.blogpost = postData;
      axios({
          method: 'post',
          url: myUrl,
          responseType: 'json',
          data: uploadData
        })

The issue arises when delete o.info; also removes the property from my root vm data. I am puzzled by this behavior as I clearly copied the data into a new variable. How can I solve this problem and remove specific object properties without affecting my root vm data in Vue?

Answer №1

To ensure your data remains intact, it is essential to create a duplicate by cloning it. One effective method for this task is utilizing the cloneDeep function from the lodash library.

import _ from 'lodash'
...
postDataCopy = _.cloneDeep(postData)

This allows you to make alterations to postDataCopy without impacting the original dataset.

Answer №2

One reason for this behavior is that in JavaScript, objects are copied by reference. This means that when you change the postData object, it is actually still pointing to the original data stored at the address of rows. To create a true copy of the data, you can use the following method:

postData = JSON.parse(JSON.stringify(rows))

Answer №3

To ensure your variable is not altered, it's important to create a duplicate of it.

// ES6
let duplicatedObject = Object.assign({}, initialObject)

Answer №4

When dealing with reference and value types in JavaScript, it's important to understand the concept of deep copying. The Object.assign method can be used to create a shallow copy of an object or array, but it only works for value types like numbers, strings, and booleans.

For example:

var user = {
name: "abc",
address: "cde"
};

var copiedUser = Object.assign({}, user); 

In this case, both user and copiedUser are different objects because they contain only value types.

However, if your object contains reference types like nested objects, the shallow copy created by Object.assign will not fully separate the two objects:

var user = {
name: "abc",
address: "cde",
other_info: { // reference type
   country: "india"
}

};

var copiedUser = Object.assign({}, user); 

Changes made to properties that are value types will not affect the original object, but changes to reference types will impact both objects:

copiedUser.name ="new name"; // will not reflect in user

copiedUser.other_info.country = "new country";
// will reflect in user also

To create a deep copy of an object with nested objects or arrays, you need to iterate through each level and perform the copy operation:

var rows = [
{
title: "my title",
post: "my post text",
public: false,
info: "some info"
},
{
title: "my title",
post: "my post text",
public: true,
info: "some info"
},
{
title: "my title",
post: "my post text",
public: false,
info: "some info"
}
];

var postData = [];

for(var i=0;i<rows.length;i++) {
postData.push(Object.assign({}, rows[i]));
}

Answer №5

The presence of Observer _proto within each object and array is what triggers reactivity.

If necessary, you can incorporate the following object utility mixin to eliminate observable characteristics from each object.

const isEmpty = (value) => {

if (!value) return false;

if (Array.isArray(value)) return Boolean(value.length);

return value ? Boolean(Object.keys(value).length) : false;

};

const isNotEmpty = value => isEmpty(value);

const clone = (value) => {

if (!value) return value;

const isObject = (typeof value === 'object');

const isArray = Array.isArray(value);

if (!isObject && !isArray) return value;

// Removing reference of Array of values

if (isArray) return [...value.map(val => clone(val))];

if (isObject) return { ...value };

return value;

};

const merge = (parent, values) => ({ ...parent, ...values });

export {

isEmpty,

isNotEmpty,

clone,

merge

};

Additionally, in the store getters section:

import { clone } from '@/utils/object';

const getData = state => clone(state.data);
export default {
   getData
}

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

Height of VUE Carousel 3D Slider dimension

I recently integrated the VUE Carousel 3D Slider on my website, but I'm facing an issue with controlling the height of the slides. There seems to be excessive space below the slider because the slides are unnecessarily tall. I attempted to adjust the ...

Utilizing the outcome of the initial promise in subsequent promises within a Promise.all operation

After finding a helpful answer by T.J. Crowder on a SO Thread, I successfully combined a loop of async tasks with Promise.all. The main issue at hand is that I need to first read an excel file in one Promisified function and a list of image files in anothe ...

Exploring the integration of polyfills and the jQuery package in Next.js

Encountering a problem related to the Next.js array-flat polyfill. It is essential for me to have compatibility with older versions of Chrome, specifically in the range from v60 to v68. The project I am currently working on utilizes a video player library ...

Send the content of an HTML file to a JavaScript variable

I'm working on using a template.html file as an email template in loopback/nodejs. In PHP, I know how to include the template.php file and store it in a variable like this: ob_start(); include template.php; $template = ob_get_clean(); Is there a way ...

What is the best way to attach an event again in jQuery?

My JavaScript/jQuery code initiates a listener to highlight DOM elements when a button is clicked. By clicking the button, the listener event starts (e.g. highlight : function()). If I click on any part of the webpage, the listener stops. However, if I ...

Is it possible to pass data into an AngularJS controller without relying on routes?

In my angular application, there is a controller that requires server-side initialization to happen before it is instantiated. I need this initialization process to be done synchronously so that the data can be fetched prior to the controller being called. ...

What is the method for selecting the col/row or x/y coordinates for N random elements from a 2D matrix without repeating any items or coordinates?

In my dataset, which is a 2D matrix, here is an example: data = [["a", "b", "c", "d"], ["e", "g"], ["i", "j", "k"]] I am looking to retrieve N random (x, y) indexes without any duplicates. Previously, I had a similar question and here is the solution I f ...

Uploading multiple files via AJAX without any files being uploaded

I have been attempting to upload multiple files with just one AJAX request. However, I am encountering some issues, including: UPDATE No files are being successfully uploaded to the server It appears that multiple AJAX requests are being triggered due t ...

Issue with vue.js and webpack: Unable to add a plugin to vue.config.js using configureWebpack

Problem with vue.js webpack: Unable to add a plugin to vue.config.js using configureWebpack I have set up a vue.js project using vue cli 3. I am following the example provided in: https://cli.vuejs.org/guide/webpack.html This is how my vue.config.js file ...

JavaScript Instant Validation: Ensuring Accuracy in Real-Time

I am trying to create a JavaScript code that validates user input based on certain rules. If the input does not meet the criteria, I want an error message to appear next to the text field. For instance, if the rule is that the first character must be a cap ...

Using the JS confirm function to switch the Vuetify checkbox in a Vue 2 application

It's been a real struggle trying to figure out this issue. I have a v-dialog that contains a checkbox. When the checkbox is clicked, a confirm() method is triggered to open a dialog in the browser to confirm the selection. After confirming, the check ...

What could be the reason behind React useState impacting several instances of the identical component?

I have a situation where I created a component that expands when a button is clicked using the useState hook. The issue arises when multiple instances of this component are mapped and one expand button click causes all of them to expand. How can I resolve ...

Confusion arises between Bootstrap button plugin and Vue checkbox click event

After incorporating bootstrap.min.js into my Vue app, I noticed that the checkboxes' @click event is no longer triggered. This issue specifically occurs when using bootstrap's button-group with data-toggle="buttons". If I remove bootstrap.min.js, ...

What do you do when schema.parseAsync cannot be found?

Currently facing an issue with zod validation in my Node.js environment, specifically encountering the error: TypeError: schema.parseAsync is not a function Despite attempting various solutions like re-importing and troubleshooting, I am unable to resol ...

What is the best way to reset the selected label in a React Material AutoComplete component when the state is

I currently have a state declared as: const [searchEntryNo, setSearchEntryNo] = useState(''); In addition, there is a function set up to clear the state when needed. const handleClear = () => { setSearchEntryNo(''); }; Ne ...

Showing an image based on the selected value from a dropdown menu using jQuery

I am trying to dynamically display the correct image based on the option selected in a dropdown menu. Currently, I am able to show the image if the option value matches the filename; however, I need help with displaying the image using echo rather than t ...

The HTML required attribute seems to be ineffective when using AJAX for form submission

Having trouble with HTML required attribute when using AJAX submission I have set the input field in a model Form to require attribute, but it doesn't seem to work with ajax. <div class="modal fade hide" id="ajax-book-model" a ...

Ways to Read JSON without Using jQuery

Exploring JSON Feed and Autocomplete As I delve into the realm of creating an autocomplete feature that fetches data from a JSON feed, I encounter a setback. Despite successfully parsing the JSON data using json2.js through JSON.parse, I am confronted wit ...

Rendering a page for a missing resource

Within the App.js file, the routes component is currently only wrapping a portion of the website. However, I would like the NotFound component to be rendered for the entire page if an incorrect URL is entered. Can you please provide guidance on how this ...

Utilize class for sending ajax data instead of using ID

I have a dynamic PHP-generated form: <form id="change_status_form" name="change_status_form"> <input name="booking_int" type="hidden" value="'.$upcoming_bookings[$x]['booking_int'].'"> <select name="booking_status" oncha ...