How to copy a JavaScript object? [duplicate] - javascript

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/

Related

Clone object created with new in JavaScript [duplicate]

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.

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.

Do Javascript variable assignments work by reference? [duplicate]

This question already has answers here:
JavaScript by reference vs. by value [duplicate]
(4 answers)
Closed 8 years ago.
I have a question about referencing objects in javascript.
Say I have a variable that is some object (lets say json) and it is called objOne - (var objOne = someJSONObject;).
If I go ahead and declare
var objTwo = objOne;
will I have two references to the same Object? Kind of like a c pointer?
To sum it up :
assignements are done by value
you never manipulate objects, only object references
This means that
you'll have two references to the same object (you can check that by changing a property of the object)
when you're passed in a variable the value of a primitive, changing your variable doesn't change other variables
EDIT : as it's a duplicate I'll delete this answer in a minute to allow a proper closing if there's no other answer. Please vote to close.
Yes, objects are passed by reference:
function changeVal(obj){
obj.value = "bar"
}
(function checkRefs(){
var myObject = {
value: "foo"
};
alert(myObject.value);
changeVal(myObject);
alert(myObject.value);
})();

Convert static object to dynamic [duplicate]

This question already has answers here:
Adding Prototype to JavaScript Object Literal
(5 answers)
Closed 9 years ago.
If I have an object like this:
var obj = {};
I can't extend it because it hasn't got any prototype.
Is there any way to convert this object to dynamic so that it's possible to extend it and use new keyword. Something like:
obj.prototype.property = 'value';
var newobj = new obj;
That has nothing to do with static or dynamic.
You can only use the new operator on functions, not objects.
You cannot turn an object into a function; you need to create it as a function in the first place.
the only way is the following:
var obj = function () {};
because you can only use the new keyword with constructor function. That's it!

Dynamically assign name to object array [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 10 years ago.
I have a javascript issue.
If I have an object array objAr, the object consists of id,name.
If I was to access objAr[0].id it returns the id value of the first object. What would happen if the object is dynamic and therefore I do not know what it consists of, is there a way to dynamically call the Object attribute?
Currently I am creating another array
var theArr = new Array("id", "name");
and call:
objAr[0].theArr[0] instead of objAr[0].id.
Is there a way to do this better using Javascript?
With Javascript you can call all of the attributes in an object without knowing the keys.
See below:
for(key in objAr[0]) {
console.log(objAr[0][key]);
}
If you just wanted the first attribute you could run:
for(key in objAr[0]) {
var attFirst = objAr[0][key];
break;
}
Additionally for the JS array you could have used square brackets.
var theArr = ["id", "name"];
hope that helps
In javascript you can always use the "array notation" in place of the "dot notation"
So these 2 lines are the same
objAr[0].id
objAr[0]["id"]

Categories

Resources