Clone object created with new in JavaScript [duplicate] - javascript

This question already has answers here:
How do I clone a JavaScript class instance?
(6 answers)
Closed 5 years ago.
I am trying to clone an object created with new. The only way I found to do it is:
let tmp = Object.create(instance.__proto__);
let obj = Object.assign(tmp, instance);
This examples works and does the job, but doesn't look like a proper solution. I was wondering if there is a better way to clone the object created with new?
Any help will be appreciated!

It all depends if you want to make a deep or shallow clone.
For the simplicity let's assume that you want to create a shallow clone as in your code.
Then, you can either use shorter version of the code you provided:
let obj = Object.assign({}, instance);
Or use ES6 spread syntax:
let obj = {...instance};
Both ways are correct.

Related

Need a copy of value. No need referenced value [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 4 years ago.
I just need to copy the value of data.notes. I have used below code. But still detailsOfCurrentNotes value changes according to the value of data.notes. So could you tell me how to do this?
notes :Note[]
const detailsOfCurrentNotes = Object.assign({}, data.notes);
//here data.notes changes
// detailsOfCurrentNotes also get that value
If the object/array is not circular, you can simply do:
const detailsOfCurrentNotes = JSON.parse(JSON.stringify(data.notes));
If notes is an array, it is:
const detailsOfCurrentNotes = Object.assign([], data.notes);
And shorter syntax is:
const detailsOfCurrentNotes = [...data.notes];
This creates shallow copy of an array.

how to copy an object over another without the two referencing each other? [duplicate]

This question already has answers here:
How do I correctly clone a JavaScript object?
(81 answers)
Closed 5 years ago.
Let's say we got this:
this.myObject = {"id":1};
and we want to store the state of my object as my object original as the following:
this.myObjectORG = this.myObject;
then you go on your business and change props on your object like this
this.myObject.id = 2;
and to your surprise down the road, you realize that
console.log (this.myObjectORG.id) // also reports 2
Well, that's just how JS works & I'm not questioning that.
Is there a way to preserve the state of the myObject so I can do comparisons whether its properties changed since its original state?
At some point I'd like to be able to do something like this
if ( this.myObjectORG.id !== this.myObject.id ) {
// but this condition is never true
}
Does this help:-
An Object.assign method is part of the ECMAScript 2015 (ES6) standard and does exactly what you need.
var this.myObjectORG = Object.assign({}, this.myObject);
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

Hard Copy vs Shallow copy javascript [duplicate]

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed 6 years ago.
This may be an old question but I'm really curious about the nature of copying objects by reference as an assignment in javascript.
Meaning that if
var a = {};
var b = a;
a.name = "Renato";
console.log(b);
Object {name: "renato"}
I'm kind of new to javascript and this really caught my attention to have a shallow copy as a default for Object assignment. I searched that in order to create a hard copy, you have to create a mixin. I was wondering why was this chosen as the default since it's transformation seems to be very implicit. Thanks!
Objects and arrays are treated as references to the same object. If you want to clone the object, there are several ways to do this.
In later browsers, you can do:
var b = Object.assign({}, a);
If you want to go for a library, lodash provides _.clone (and _.cloneDeep):
var b = _.clone(a);
If you don't want to do either of those methods, you can just enumerate through each key and value and assign them to a new object.
Oftentimes it's valuable for them to be treated as references when passing through multiple functions, etc. This isn't the case for primitives like numbers and strings, because that would feel pretty counterintuitive in most cases.

How to copy a JavaScript object? [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 8 years ago.
I am using a plain JavaScript object. I have to create an exact copy of the object to make changes:
var gRoll = {a:"pankaj",b:
{
a:"A",b:"c"
}}
var copy = gRoll;
copy.a = "Karma";
This is making change in the parent object. Please give me solution to create copy of the object without referring to the old one. Same like prototype design pattern in OOPS.
You're referencing the same object with copy
var gRoll = {
a:"pankaj",
b:{a:"A",b:"c"}
}
var newObject = Object.create(gRoll);
newObject.a = 'Karma';
alert(gRoll.a); //pankaj
alert(newObject.a); //Karma
what you are doing is not creating a copy but referring to the existing object with a new variable, hence the issue.
If you are using jQuery, use its extend() method which copies an exiting object... with optional parameter for deep-copying.
http://api.jquery.com/jquery.extend/

Javascript. Swap two variables. How it works? [duplicate]

This question already has answers here:
javascript variable swapping using arrays
(3 answers)
Closed 8 years ago.
Saw in a single source next:
[param_o,param_got] = [param_got,param_o];
This code swap variables param_o & param_got.But how [param_o,param_got] = [param_got,param_o] works, if [] is new instance of Array in Javascript ?
EDIT
Try checking:
var param_o = 1;
var param_got = 2;
[param_o,param_got] = [param_got,param_o];
console.log(param_o+" "+param_got);
// 2 1
This notation is called destructuring assignment and is part of Javascript 1.7:
Destructuring assignment makes it possible to extract data from arrays
or objects using a syntax that mirrors the construction of array and
object literals.
The object and array literal expressions provide an easy way to create
ad-hoc packages of data. Once you've created these packages of data,
you can use them any way you want to. You can even return them from
functions.
One particularly useful thing you can do with destructuring assignment
is to read an entire structure in a single statement.
The first sample actually demonstrates explicitly that this is useful to avoid temporary variables as in your code sample.
Firefox has supported this feature since Firefox 2 already. For Chrome the bug is still open after 3 years. IE11 doesn't support it either from what I've just tested.

Categories

Resources