I'm curious why these methods seem to vanish once I make a copy of the array

There seems to be a strange occurrence happening with the data below:

// data
visitorsTemplate: [{
  text: '',
  type: 'buttons',
  children: [{
    name: 'email',
    method: (e) => { this.sendEmail(e) }
  }]
}]

When it is cloned using the following function:

// watch
console.log(this.visitorsTemplate)
const visitorItem = clone(this.visitorsTemplate)
console.log(visitorItem)

Utilizing this cloning function:

// utils
export const clone = (...args) => {
  return JSON.parse(JSON.stringify.apply(null, args))
}

The method attribute mysteriously disappears after the cloning process. The console logs show the changes made:

[{
  text: "",
  type: "buttons",
  children": [{
    name: "email",
    method: f method(e)
  }, {
    name: "delete",
    method: f method(e)
  }]
}]

[{
  text: "",
  type: "buttons",
  children": [{
    name: "email"
  }, {
    name: "delete"
  }]
}]

Update: It has been discovered that JSON.stringify is causing the removal of the methods, but in order to create a new array while retaining these methods, what steps should be taken?

Answer №1

If you're looking to create a deep copy of an object, you can write your own implementation like the following example:

    function customDeepClone(obj) {
        var cloneObj = {};
        for(var prop in obj) {
            if(obj[prop] != null && typeof(obj[prop]) === "object") {
                cloneObj[prop] = customDeepClone(obj[prop]);
            } else {
                cloneObj[prop] = obj[prop];
            }
        }
        return cloneObj;
    }

Answer №2

Looking into the JSON Specs here, it's clear that JSON does not include methods, only data. The use of stringify followed by parsing introduces JSON as an intermediary step, resulting in this issue.

For more insights on cloning arrays of objects, check out this post.

I hope this explanation is helpful!

Answer №3

Once you use JSON.stringify, it will convert your JSON object into a string. If there is a method inside the object, it will also be converted to a string.

If you need a new instance of the object, you can achieve this by using: http://underscorejs.org/#clone

newObject = _.clone(visitor)

Alternatively, if you want to create objects programmatically later on, you can prepare these functions:

function Visitor(){
    return {
    text: '',
    type: 'buttons',
    children: [Child()]
   }
}

function Child(){
    return  {
       name: 'email',
       method: (e) => { this.sendEmail(e) }
   }
}

Answer №4

Employ Object.assign in combination with Array.prototype.map

const copyOfArray = array.map(item => Object.assign({}, item));

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

Simulated script in a different component

I am looking to simulate the functionality of Amazon AWS S3 getObject The specific code I aim to test is located in helper.js var AWS = require('aws-sdk'); var s3 = new AWS.S3(); exports.get_data_and_callback = function(callback, extra){ s3. ...

Is there a way to direct Webpack in a Next.JS application to resolve a particular dependency from an external directory?

Is it possible to make all react imports in the given directory structure resolve to react-b? |__node_modules | |__react-a | |__app-a | |__component-a | |__next-app | |__react-b | |__component-b // component-a import { useEffect } from ' ...

"Authorization refused" notification on Internet Explorer 6

Encountering an error in IE6 on line 10 with this code. Specifically, var ref = ...; What could be causing the issue here? <html> <head> <title>JavaScript Popup Example 3</title> </head> <SCRIPT language="JavaScript1.2"& ...

Steps to create a thumbnail image following the insertion of an image into an input type="file" within a form, and subsequently submitting both elements on the form together

Currently, I am working on a form that enables users to upload images. Once the user submits the form, my goal is to create thumbnails for each image on the front-end and save them on the server afterwards. Due to security restrictions, changing the value ...

Converting a jQuery DOM element into a string representation

Currently, I am working with a textarea that contains the contents of an HTML file. This textarea includes all elements of my HTML page such as doctype, head, html, etc. My goal is to save the content of the textarea into a DOM variable using $.parseHTML: ...

jQuery ajaxSetup: handling error retries for ajax calls is not possible

When using $.ajaxSetup(), I am faced with the challenge of making an AJAX request after refreshing a valid token in case the previous token has expired. The issue arises when attempting to execute $.ajax(this) within the error callback. $.ajax({ url: ...

Breaking content into two sections using Javascript or jQuery

Uncertain if Javascript can handle this task, any assistance or advice is appreciated. Consider this scenario: Suppose I have a 6-paragraph long content (text only) being pulled dynamically from the database all at once. This means that all 6 paragraphs a ...

Combining an Angular factory with another factory

I'm facing some difficulties with injecting one factory into another. The error message I'm getting is: `ReferenceError: testDataService is not defined` I thought it would be a simple issue to resolve, but it's turning out to be quite c ...

How can I make sure the return statement in getServerSideProps is only executed once all fetching operations are finished?

Currently, I am able to retrieve a person's username and corresponding data object with just one fetch from firebase. Inside this data object, there is a property named "uploads," which contains an array of documentIDs representing posts uploaded by t ...

Utilizing media queries to customize the appearance of a jQuery accordion widget

Hello, I'm struggling with implementing a jQuery accordion for mobile platforms that destroys itself on larger screens. While my code is mostly working, I've encountered two issues: The accordion only gets destroyed when the window is resized ...

Sometimes the Navbar options fail to show up consistently on the Navbar bar

I recently launched my website at campusconnect.cc Unfortunately, I've noticed that when resizing the window, the navbar options are shifting up and down. Can anyone help me identify the issue and provide guidance on how to resolve it? ...

Creating Three-Dimensional Faces in THREE.BufferGeometry

I have programmatically created a basic mesh structure: var CreateSimpleMesh = new function () { var xy = [], maxX = 7, maxY = 10, river = [[0, 5], [0, 4], [1, 3], [2, 2], [3, 2], [4, 1], [5, 1], [6, 0]], grassGeometry ...

Embracing the Legacy of jQuery's Event Handling Mechanism

I am in the process of developing an SDK for a website's API that relies on jQuery. I am interested in incorporating jQuery's custom events model into the SDK. How can I effectively integrate, encapsulate, or otherwise leverage jQuery's even ...

Unable to directly assign a variable within the subscribe() function

My goal is to fetch a single row from the database and display its information on my webpage. However, I've encountered an issue with the asynchronous nature of subscription, which prevents immediate execution and access to the data. Upon running the ...

Are current web browsers able to block the code "<a href="javascript:window.open....?

I am looking to create a pop-up window for sharing on Facebook. The best way to achieve this is by using javascript to pop up a small window with a width of 400 pixels and a height of 200 pixels. Will pop-up blockers in Chrome, IE, or Google block this f ...

What are the methods for determining if a Triangle intersects a Box3?

Is there a built-in function in THREE.js to determine if a THREE.Triangle overlaps with a THREE.Box3 object? If not, what approach can be taken to achieve this? ...

Using Vue props and @emit for communication between parent and child

I am running into issues with using a prop along with @emit in Vue and I could use some guidance on how to correct it. I want to learn a non-global registration method for handling this properly (I'm new to Vue, by the way). Below is an excerpt from ...

The selected jquery script is failing to function as intended

I'm currently implementing jQuery chosen in a select element to enhance user experience, however I'm facing an issue when attempting to copy the chosen div to another div using jQuery $(document).ready(function() { $(".chosen").chosen({}); ...

Is there a way to split a JSON string into an array using JQuery?

I need help splitting all the values from a JSON format string into an array. [{ "sno": "1", "code": "bp150mb", "quantity": null, "name": "mudguard", "company": "bajaj", "vehicle": "pulsar", "brand": "1", "image": "N/A", "color": "Blac ...

Does this Loop run synchronously?

Recently, I crafted this Loop to iterate through data retrieved from my CouchDB database. I am curious whether this Loop operates synchronously or if async/await is necessary for proper execution. database.view('test', 'getAllowedTracker&ap ...