Creating a clone of a JavaScript object based on an already existing JavaScript object

Can someone help me with this coding issue?

var originalObject = {
    method1: function() {
        // Do something
    },
    method2: ['a','b','c'],
    method3: 1234
}

I am trying to create a new object based on the original one like so:

var newObject = Object.create(originalObject);

However, the properties of the original object do not seem to be reflected in the new object. What could be causing this issue?

Answer №1

If you want to create a clone function, you can do so by following this example:

var makeClone = function(object) {

    // Create a new object with the same prototype as the original object
    var clonedObject = Object.create(object);      

    // Copy each property from the original object to the cloned object
    for (property in object) {      
        if (object.hasOwnProperty(property)) {
            clonedObject[property] = object[property];
        }
    }

    return clonedObject;  // Return the cloned object
}

NOTE: It's important to be cautious when creating the cloned object from the original one.

  1. Remember that if you use var cloned = {};, the prototypes will be different and the solution may not work perfectly because instances might not match using the instanceof operator.

  2. If you only use

    var cloned = Object.create(object);
    as suggested in other answers, you'll get a cloned object with a similar prototype. However, you still need to copy the properties from the original object to the cloned one. That's why the for-loop is necessary.

If the previous approach of using Object.create doesn't work in your browser due to a legacy JavaScript engine, you can try the workaround below:

function Temporary() {};
Temporary.prototype = object.prototype;
var clonedObject = new Temporary();

I hope this information is helpful! :)

Answer №2

To utilize the prototype method:

var newObj = Object.create(oldObj.prototype);

The Object.create function creates a fresh object with specific prototype and attributes.

It requires the prototype for the newly generated object:

Object.create(proto [, propertiesObject ])

Link to more information

Answer №3

If you're looking for an alternative method, JQuery offers a convenient solution with the Jquery.extend function. To achieve this, simply follow the syntax below:

var newObject = jQuery.extend({},originalObject);

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

Having trouble receiving a response when making a request to an API

I encountered an issue while trying to fetch an API. Initially, I received an error message stating that the message port was closed before a response was received. After removing all extensions, the error disappeared but now I am still unable to receive a ...

jQuery - Uh-oh! Looks like there is a syntax error and the

I encountered an issue with my fiddle where I am getting an error message. Any suggestions on how to effectively handle decimals and spaces within the code, specifically when using .split and join() functions, without causing an unrecognized expression e ...

Storing JSON location data in JavaScript

When converting JSON data into a list structure, I aim to use the "AAA.BBB[0].CCC.DDD[5].EEE" format as the ID. This way, any modifications made by a user to the content of that specific list item will directly affect the JSON data linked to that location. ...

An innovative concept of housing two distinct retailers under one app

I am facing an issue with my vue.js application that consists of a landing page, user dashboard, and admin dashboard. Each section has different states, but they all share a common shared module with important data like page width, token, current user, etc ...

Using ThreeJS to project a texture onto a mesh surface

I am trying to project a texture onto the surface of a mesh using ThreeJS. The link provided achieves the desired result, although I am uncertain about the method used to accomplish it. . As I continue my research, I will update this post. If anyone has ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

"Troubleshooting: The Dropzone js code sample from the documentation

I am currently implementing a tutorial from the documentation provided by Dropzone.js. However, I seem to be encountering an issue as the example is not working correctly. Here is the structure that I currently have: Dropzone.options.myAwesomeDropzone = ...

Changing the direction of the cursor to move opposite of the mouse's input

I'm currently working on a unique webpage with an unconventional navigation method. The concept involves the cursor moving in the opposite direction of mouse movement input. To achieve this effect, I decided to hide the actual cursor and use JavaScri ...

Is there a way to ensure that the function within the 'for loop' is executed prior to sending the response in NodeJS?

Utilizing bluebird for this task, my main goal is to ensure that the function `get_like_status(email, results[i].id)` located at the end of the for loop runs before sending out the headers. Currently, I am encountering an issue where the array list retur ...

What could be causing my onclick code to activate on double click the very first time?

Currently, I am developing a straightforward popup for my Nextjs website. The implementation involves using the onclick attribute to toggle the display property in CSS between none and block based on the ID of the element. Although the functionality works ...

Error: The react.js application is unable to access the property 'classList' of a null object

I've encountered a bug that's been causing me some trouble. Every time I try to run my react application, I keep getting an error message that reads TypeError: Cannot read property 'classList' of null. As someone who is new to react, I& ...

The error message "buildParams: Exceeded maximum call stack size with Uncaught RangeError" was

I'm having trouble pinpointing the mistake. Can someone please assist me? Every time I submit the form, I encounter the following error in the console: Uncaught RangeError: Maximum call stack size exceeded at buildParams I've looked at variou ...

Updating the header title in React Navigation 5.x with dynamic changes

After upgrading my project to react navigation 5.x, I encountered an issue with setting the header title. In previous versions, we used to set it like this: static navigationOptions = ({ navigation }) => ({ title: 'find', }); However ...

The Next Js 13 API route is failing to retrieve accurate data following a post request

I've been working on a project involving authentication using Django backend and Next.js frontend. For state management, I'm utilizing Redux Toolkit. However, I've encountered an issue with the Next.js API that communicates data to the backe ...

Iterate through each row of the PHP array

Hey there, I have two sets of code that I'd like to share with you. The first one is an Ajax snippet: /* Loop and Retrieve Data from Database to Generate a Table */ $(document).ready(function () { $('#btngenerate').click(function(e){ ...

Ways to join two if statements together using the or operator

Below is my code attempting to check if either child elements H1 or H2 contain text that can be stored in a variable. If not, it defaults to using the parent element's text: if($(this).children('h1').length){ markerCon[markerNum] = $(th ...

Adjusting the background opacity when the sidebar is open in a React + Typescript project

I am currently working on customizing a sidebar using the react-pro-sidebar library along with React and Typescript. The sidebar layout seems to be in order, but I am facing difficulty in adjusting the background color of the rest of the screen when the si ...

A straightforward interval-based Ajax request

I've recently delved into the world of Ajax and jQuery. Just yesterday, I embarked on creating a simple ajax request for a form that sends a select list value to a PHP script and retrieves data from a database. Things are going smoothly so far! Howev ...

What is the best way to conceal text that is not enclosed in <p> or <span> tags?

I need to hide a specific portion of text in an HTML code snippet, however, the text is not wrapped in any specific element. Here is an example: <div class="content"> Give comfortable and durable place to work with a desk. Lock the center d ...

Leaflet OSM: Adjust map focus to the polygon's center

Looking to create an HTML file that integrates the Leaflet library to display an OpenStreetMap view with a centered polygon? I've been following a helpful discussion, but still unsure about how to center and autozoom an arbitrary polygon on the map. A ...