get a duplicate of an object

Is this the proper method for creating a duplicate of an object?

class ObjectWrapper {
  private _obj;

  /***
   * Copy object passed as argument to this._obj
   */
  constructor (_obj: Object) {
    this._obj = _obj;
  }

  /** 
   Return copy of this._obj (Return copied version of this._obj)**
   * @return Object
   */ 
  get obj() {
    return this._obj;
  }

I am curious about the concept of "returning a copy."

Answer №1

Copying an object in JavaScript can be done in a few different ways, one of which is using the Object.assign() method.

A traditional way to copy an object is through Object.assign():

const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

Keep in mind that Object.assign() only copies enumerable and own properties from the source object to the target object.

source

Another approach is using the spread operator in ESNext:

const source = { a: 1, b: 2 };
const target = {...source};

This feature, part of the Rest/Spread Properties for ECMAScript proposal (stage 4), allows for copying own enumerable properties from one object to another.

source

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

Changing a file object into an image object in AngularJS

Can a file object be converted to an image object? I am in need of the width and height from the file (which is an image). Here is my code: view: <button id="image_file" class="md-button md-raised md-primary" type="file" ngf-select="uploadFile($file ...

encountering difficulties when trying to install npm packages in node.js

Starting out with Node.js and new to installing packages like express.js and underscore.js using NPM. However, every time I attempt to install using the following commands: npm install express, npm install underscore I keep encountering errors. Please ...

Executing a Node.js script using an absolute path

In the process of developing a basic app using Node.js and Express, I've encountered an issue. The script is located at path/to/script/server.js. When I run this script with node server.js while in the correct directory, everything functions correctly ...

When running npm run build, an error with the error code ELIFECYCLE is

For some time now, I have been following the "ES6 for everyone" series by Wes Bos, but I hit a roadblock while trying to tackle a webpack episode. Every time I attempt to execute the "npm run build" command in my CMD prompt, I encounter this error: npm ...

Creating multiple tabs in PHP using the header function can be achieved by specifying the location in

I am attempting to open a new tab using Php code: header("location:print_register.php?recpt_no=".$recpt_no); In addition, I would like to open two tabs programmatically with the following code snippet: header("location:print_register.php?recpt_no=".$rec ...

React component state remains static despite user input

I am currently in the process of developing a basic login/signup form using React, Typescript (which is new to me), and AntDesign. Below is the code for my component: import React, { Component } from 'react' import { Typography, Form, Input, But ...

Manage and preserve your node.js/express sessions with this offer

Currently, I am working on a web application that encounters an issue where every time fs.mkdir is called, all the current express sessions are deleted. This causes me to lose all session data and I need a solution to keep these sessions intact. I have att ...

Tips for avoiding cropped images on mobile websites:

I recently created a website that looks perfect on desktop but appears cropped on mobile devices. The site in question is doc.awsri.com Here are the images causing the issue: https://i.stack.imgur.com/eRJXU.png The problem arises when viewing it on a ph ...

The issue where all buttons in a list are displaying the same ID

I am facing an issue with a row of buttons, all having the same class add-btn. Whenever I click on one button, I intend to log the id of its containing span. However, currently, all buttons are logging the span id of the first add-btn in the list. $(&apos ...

Is there a way to create a Vue.js component that retains the data I have added to it even when transitioning between routes? Currently, whenever I switch routes, the component deletes all the previously

I'm currently working on a webshop using Vue.js. When I add products, I utilize an event bus to pass the data to the CartComponent. Everything works as expected; however, if I navigate back or reload the page, all the data in my CartComponent gets del ...

React: Unable to locate an index signature with a parameter of type 'string' on type N

While working with a React component, I encountered an issue when trying to access a property from my component state using a key. My editor showed the following warning: Element implicitly has an 'any' type because expression of type 'str ...

What is the best way to print a canvas element once it has been modified?

My goal is to include a "Print Content" button on a webpage that will print a canvas element displaying workout metrics. However, the canvas content, which consists of a visual graph of workout data, changes based on the selected workout (bench, squat, etc ...

Is there a way to link table A's ID to table B's userID in a postgreSQL database?

Is it possible in PostgreSQL to establish a relational index between table A ID and table B userId for the purpose of joining two tables based on their ids? To provide further clarification, here is an example using MongoDB and Mongoose: const Billing = ...

Leveraging backstretch.js in combination with blur.js (or equivalent)

Query Update I provided a response to the query below, however, I am experiencing some lag and a noticeable stepped transition between images. Can anyone offer advice on how to optimize this issue? Perhaps it would be better to go back to using a static ...

Filtering properties of objects in Vue

I am currently dealing with an array of objects that represent continents: data() { return { continents: [ { name: "South America", countries: [ { name: "P ...

Setting up craco for jsx in your project

I am currently utilizing craco and grappling with how to configure jsx. I keep encountering the error below: Support for the experimental syntax 'jsx' isn't currently enabled (4:17): The suggestion is to add `babel/preset-react or utilize ...

AngularJS - Alter the URL with $state.go without refreshing the HTML content

Struggling with routing in angularJS and can't seem to find a solution despite trying various methods online. Any assistance would be greatly appreciated. Encountering an issue with the $state.go function in which it changes the URL but fails to load ...

Technique for identifying a sequence within a longer numerical series

As I ponder this puzzle for what seems like an eternity, I humbly turn to you for a possible solution. A lengthy number resembling this one: 122111312121142113121 It is crucial to note that no numbers exceed four or fall below one. Now my quest is to une ...

Bidirectional data binding with Observable object

I have been trying to connect isSelected to an object wrapped in an observable. When I attempted this without the observable, it worked perfectly fine. However, within my component, I am facing an issue where measure.isSelected always returns false, even w ...

What is the process for adding JSON data to a dropdown menu using PHP AJAX?

I am trying to populate a select html element with data from a list of JSON results. Here is the code I have attempted: JSON output: jquery loop on Json data using $.each {"Eua":"Eua","Ha'apai":"Ha'apai",& ...