Object.freeze() seems like a transitional convenience method to move towards using const in ES6.
Are there cases where both take their place in the code or is there a preferred way to work with immutable data?
Should I use Object.freeze() until the moment all browsers I work with support const then switch to using const instead?
const and Object.freeze are two completely different things.
const applies to bindings ("variables"). It creates an immutable binding, i.e. you cannot assign a new value to the binding.
Object.freeze works on values, and more specifically, object values. It makes an object immutable, i.e. you cannot change its properties.
In ES5 Object.freeze doesn't work on primitives, which would probably be more commonly declared using const than objects. You can freeze primitives in ES6, but then you also have support for const.
On the other hand const used to declare objects doesn't "freeze" them, you just can't redeclare the whole object, but you can modify its keys freely. On the other hand you can redeclare frozen objects.
Object.freeze is also shallow, so you'd need to recursively apply it on nested objects to protect them.
var ob1 = {
foo : 1,
bar : {
value : 2
}
};
Object.freeze( ob1 );
const ob2 = {
foo : 1,
bar : {
value : 2
}
}
ob1.foo = 4; // (frozen) ob1.foo not modified
ob2.foo = 4; // (const) ob2.foo modified
ob1.bar.value = 4; // (frozen) modified, because ob1.bar is nested
ob2.bar.value = 4; // (const) modified
ob1.bar = 4; // (frozen) not modified, bar is a key of obj1
ob2.bar = 4; // (const) modified
ob1 = {}; // (frozen) ob1 redeclared
ob2 = {}; // (const) ob2 not redeclared
Summary:
const and Object.freeze() serve totally different purposes.
const is there for declaring a variable which has to assinged right away and can't be reassigned. variables declared by const are block scoped and not function scoped like variables declared with var
Object.freeze() is a method which accepts an object and returns the same object. Now the object cannot have any of its properties removed or any new properties added.
Examples const:
Example 1: Can't reassign const
const foo = 5;
foo = 6;
The following code throws an error because we are trying to reassign the variable foo who was declared with the const keyword, we can't reassign it.
Example 2: Data structures which are assigned to const can be mutated
const object = {
prop1: 1,
prop2: 2
}
object.prop1 = 5; // object is still mutable!
object.prop3 = 3; // object is still mutable!
console.log(object); // object is mutated
In this example we declare a variable using the const keyword and assign an object to it. Although we can't reassign to this variable called object, we can mutate the object itself. If we change existing properties or add new properties this will this have effect. To disable any changes to the object we need Object.freeze().
Examples Object.freeze():
Example 1: Can't mutate a frozen object
object1 = {
prop1: 1,
prop2: 2
}
object2 = Object.freeze(object1);
console.log(object1 === object2); // both objects are refer to the same instance
object2.prop3 = 3; // no new property can be added, won't work
delete object2.prop1; // no property can be deleted, won't work
console.log(object2); // object unchanged
In this example when we call Object.freeze() and give object1 as an argument the function returns the object which is now 'frozen'. If we compare the reference of the new object to the old object using the === operator we can observe that they refer to the same object. Also when we try to add or remove any properties we can see that this does not have any effect (will throw error in strict mode).
Example 2: Objects with references aren't fully frozen
const object = {
prop1: 1,
nestedObj: {
nestedProp1: 1,
nestedProp2: 2,
}
}
const frozen = Object.freeze(object);
frozen.prop1 = 5; // won't have any effect
frozen.nestedObj.nestedProp1 = 5; //will update because the nestedObject isn't frozen
console.log(frozen);
This example shows that the properties of nested objects (and other by reference data structures) are still mutable. So Object.freeze() doesn't fully 'freeze' the object when it has properties which are references (to e.g. Arrays, Objects).
Let be simple.
They are different. Check the comments on the code, that will explain each case.
Const - It is block scope variable like let, which value can not reassignment, re-declared .
That means
{
const val = 10; // you can not access it outside this block, block scope variable
}
console.log(val); // undefined because it is block scope
const constvalue = 1;
constvalue = 2; // will give error as we are re-assigning the value;
const obj = { a:1 , b:2};
obj.a = 3;
obj.c = 4;
console.log(obj); // obj = {a:3,b:2,c:4} we are not assigning the value of identifier we can
// change the object properties, const applied only on value, not with properties
obj = {x:1}; // error you are re-assigning the value of constant obj
obj.a = 2 ; // you can add, delete element of object
The whole understanding is that const is block scope and its value is not re-assigned.
Object.freeze:
The object root properties are unchangeable, also we can not add and delete more properties but we can reassign the whole object again.
var x = Object.freeze({data:1,
name:{
firstname:"hero", lastname:"nolast"
}
});
x.data = 12; // the object properties can not be change but in const you can do
x.firstname ="adasd"; // you can not add new properties to object but in const you can do
x.name.firstname = "dashdjkha"; // The nested value are changeable
//The thing you can do in Object.freeze but not in const
x = { a: 1}; // you can reassign the object when it is Object.freeze but const its not allowed
// One thing that is similar in both is, nested object are changeable
const obj1 = {nested :{a:10}};
var obj2 = Object.freeze({nested :{a:10}});
obj1.nested.a = 20; // both statement works
obj2.nested.a = 20;
Thanks.
var obj = {
a: 1,
b: 2
};
Object.freeze(obj);
obj.newField = 3; // You can't assign new field , or change current fields
The above example it completely makes your object immutable.
Lets look following example.
const obj = {
a: 1,
b: 2
};
obj.a = 13; // You can change a field
obj.newField = 3; // You can assign new field.
It won't give any error.
But If you try like that
const obj = {
a: 1,
b: 2
};
obj = {
t:4
};
It will throw an error like that "obj is read-only".
Another use case
const obj = {a:1};
var obj = 3;
It will throw Duplicate declaration "obj"
Also according to mozilla docs const explanation
The const declaration creates a read-only reference to a value. It
does not mean the value it holds is immutable, solely that the
variable identifier can not be reassigned.
This examples created according to babeljs ES6 features.
Related
I am copying objA to objB
const objA = { prop: 1 },
const objB = objA;
objB.prop = 2;
console.log(objA.prop); // logs 2 instead of 1
same problem for Arrays
const arrA = [1, 2, 3],
const arrB = arrA;
arrB.push(4);
console.log(arrA.length); // `arrA` has 4 elements instead of 3.
It is clear that you have some misconceptions of what the statement var tempMyObj = myObj; does.
In JavaScript objects are passed and assigned by reference (more accurately the value of a reference), so tempMyObj and myObj are both references to the same object.
Here is a simplified illustration that may help you visualize what is happening
// [Object1]<--------- myObj
var tempMyObj = myObj;
// [Object1]<--------- myObj
// ^
// |
// ----------- tempMyObj
As you can see after the assignment, both references are pointing to the same object.
You need to create a copy if you need to modify one and not the other.
// [Object1]<--------- myObj
const tempMyObj = Object.assign({}, myObj);
// [Object1]<--------- myObj
// [Object2]<--------- tempMyObj
Old Answer:
Here are a couple of other ways of creating a copy of an object
Since you are already using jQuery:
var newObject = jQuery.extend(true, {}, myObj);
With vanilla JavaScript
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var newObject = clone(myObj);
See here and here
deep clone object with JSON.parse() and JSON.stringify
// Deep Clone
obj = { a: 0 , b: { c: 0}};
let deepClone = JSON.parse(JSON.stringify(obj));
refrence: this article
Better reference: this article
To sum it all up, and for clarification, there's four ways of copying a JS object.
A normal copy. When you change the original object's properties, the copied object's properties will change too (and vice versa).
const a = { x: 0}
const b = a;
b.x = 1; // also updates a.x
A shallow copy. Top level properties will be unique for the original and the copied object. Nested properties will be shared across both objects though. Use the spread operator ...{} or Object.assign().
const a = { x: 0, y: { z: 0 } };
const b = {...a}; // or const b = Object.assign({}, a);
b.x = 1; // doesn't update a.x
b.y.z = 1; // also updates a.y.z
A deep copy. All properties are unique for the original and the copied object, even nested properties. For a deep copy, serialize the object to JSON and parse it back to a JS object.
const a = { x: 0, y: { z: 0 } };
const b = JSON.parse(JSON.stringify(a));
b.y.z = 1; // doesn't update a.y.z
A full deep copy. With the above technique, property values that are not valid in JSON (like functions) will be discarded. If you need a deep copy and keep nested properties that contain functions, you might want to look into a utility library like lodash.
import { cloneDeep } from "lodash";
const a = { x: 0, y: { z: (a, b) => a + b } };
const b = cloneDeep(a);
console.log(b.y.z(1, 2)); // returns 3
Using Object.create() does create a new object. The properties are shared between objects (changing one also changes the other). The difference with a normal copy, is that properties are added under the new object's prototype __proto__. When you never change the original object, this could also work as a shallow copy, but I would suggest using one of the methods above, unless you specifically need this behaviour.
Try using the create() method like as mentioned below.
var tempMyObj = Object.create(myObj);
This will solve the issue.
Try using $.extend():
If, however, you want to preserve both of the original objects, you
can do so by passing an empty object as the target:
var object = $.extend({}, object1, object2);
var tempMyObj = $.extend({}, myObj);
use three dots to spread object in the new variable
const a = {b: 1, c: 0};
let d = {...a};
As I couldn't find this code anywhere around suggested answers for shallow copy/cloning cases, I'll leave this here:
// shortcuts
const {
create,
getOwnPropertyDescriptors,
getPrototypeOf
} = Object;
// utility
const shallowClone = source => create(
getPrototypeOf(source),
getOwnPropertyDescriptors(source)
);
// ... everyday code ...
const first = {
_counts: 0,
get count() {
return ++this._counts;
}
};
first.count; // 1
const second = shallowClone(first);
// all accessors are preserved
second.count; // 2
second.count; // 3
second.count; // 4
// but `first` is still where it was
first.count; // just 2
The main difference compared to Object.assign or {...spread} operations, is that this utility will preserve all accessors, symbols, and so on, in the process, including the inheritance.
Every other solution in this space seems to miss the fact cloning, or even copying, is not just about properties values as retrieved once, but accessors and inheritance might be more than welcome in daily cases.
For everything else, use native structuredClone method or its polyfill 👋
This might be very tricky, let me try to put this in a simple way. When you "copy" one variable to another variable in javascript, you are not actually copying its value from one to another, you are assigning to the copied variable, a reference to the original object. To actually make a copy, you need to create a new object use
The tricky part is because there's a difference between assigning a new value to the copied variable and modify its value. When you assign a new value to the copy variable, you are getting rid of the reference and assigning the new value to the copy, however, if you only modify the value of the copy (without assigning a new value), you are modifying the copy and the original.
Hope the example helps!
let original = "Apple";
let copy1 = copy2 = original;
copy1 = "Banana";
copy2 = "John";
console.log("ASSIGNING a new value to a copied variable only changes the copy. The ogirinal variable doesn't change");
console.log(original); // Apple
console.log(copy1); // Banana
console.log(copy2); // John
//----------------------------
original = { "fruit" : "Apple" };
copy1 = copy2 = original;
copy1 = {"animal" : "Dog"};
copy2 = "John";
console.log("\n ASSIGNING a new value to a copied variable only changes the copy. The ogirinal variable doesn't change");
console.log(original); //{ fruit: 'Apple' }
console.log(copy1); // { animal: 'Dog' }
console.log(copy2); // John */
//----------------------------
// HERE'S THE TRICK!!!!!!!
original = { "fruit" : "Apple" };
let real_copy = {};
Object.assign(real_copy, original);
copy1 = copy2 = original;
copy1["fruit"] = "Banana"; // we're not assiging a new value to the variable, we're only MODIFYING it, so it changes the copy and the original!!!!
copy2 = "John";
console.log("\n MODIFY the variable without assigning a new value to it, also changes the original variable")
console.log(original); //{ fruit: 'Banana' } <====== Ops!!!!!!
console.log(copy1); // { fruit: 'Banana' }
console.log(copy2); // John
console.log(real_copy); // { fruit: 'Apple' } <======== real copy!
If you have the same problem with arrays then here is the solution
let sectionlist = [{"name":"xyz"},{"name":"abc"}];
let mainsectionlist = [];
for (let i = 0; i < sectionlist.length; i++) {
mainsectionlist[i] = Object.assign({}, sectionlist[i]);
}
In Javascript objects are passed as reference and they using shallow comparison so when we change any instance of the object the same changes is also referenced to the main object.
To ignore this replication we can stringify the JSON object.
example :-
let obj = {
key: "value"
}
function convertObj(obj){
let newObj = JSON.parse(obj);
console.log(newObj)
}
convertObj(JSON.stringify(obj));
The following would copy objA to objB without referencing objA
let objA = { prop: 1 },
let objB = Object.assign( {}, objA )
objB.prop = 2;
console.log( objA , objB )
You can now use structuredClone() for deep object clones :
https://developer.mozilla.org/en-US/docs/Web/API/structuredClone
const newItem = structuredClone(oldItem);
Serialize the original object into JSON and Deserialize to another object variable of same type. This will give you copy of object with all property values. And any modification to original object will not impact the copied object.
string s = Serialize(object); //Serialize to JSON
//Deserialize to original object type
tempSearchRequest = JsonConvert.DeserializeObject<OriginalObjectType>(s);
I am copying objA to objB
const objA = { prop: 1 },
const objB = objA;
objB.prop = 2;
console.log(objA.prop); // logs 2 instead of 1
same problem for Arrays
const arrA = [1, 2, 3],
const arrB = arrA;
arrB.push(4);
console.log(arrA.length); // `arrA` has 4 elements instead of 3.
It is clear that you have some misconceptions of what the statement var tempMyObj = myObj; does.
In JavaScript objects are passed and assigned by reference (more accurately the value of a reference), so tempMyObj and myObj are both references to the same object.
Here is a simplified illustration that may help you visualize what is happening
// [Object1]<--------- myObj
var tempMyObj = myObj;
// [Object1]<--------- myObj
// ^
// |
// ----------- tempMyObj
As you can see after the assignment, both references are pointing to the same object.
You need to create a copy if you need to modify one and not the other.
// [Object1]<--------- myObj
const tempMyObj = Object.assign({}, myObj);
// [Object1]<--------- myObj
// [Object2]<--------- tempMyObj
Old Answer:
Here are a couple of other ways of creating a copy of an object
Since you are already using jQuery:
var newObject = jQuery.extend(true, {}, myObj);
With vanilla JavaScript
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var newObject = clone(myObj);
See here and here
deep clone object with JSON.parse() and JSON.stringify
// Deep Clone
obj = { a: 0 , b: { c: 0}};
let deepClone = JSON.parse(JSON.stringify(obj));
refrence: this article
Better reference: this article
To sum it all up, and for clarification, there's four ways of copying a JS object.
A normal copy. When you change the original object's properties, the copied object's properties will change too (and vice versa).
const a = { x: 0}
const b = a;
b.x = 1; // also updates a.x
A shallow copy. Top level properties will be unique for the original and the copied object. Nested properties will be shared across both objects though. Use the spread operator ...{} or Object.assign().
const a = { x: 0, y: { z: 0 } };
const b = {...a}; // or const b = Object.assign({}, a);
b.x = 1; // doesn't update a.x
b.y.z = 1; // also updates a.y.z
A deep copy. All properties are unique for the original and the copied object, even nested properties. For a deep copy, serialize the object to JSON and parse it back to a JS object.
const a = { x: 0, y: { z: 0 } };
const b = JSON.parse(JSON.stringify(a));
b.y.z = 1; // doesn't update a.y.z
A full deep copy. With the above technique, property values that are not valid in JSON (like functions) will be discarded. If you need a deep copy and keep nested properties that contain functions, you might want to look into a utility library like lodash.
import { cloneDeep } from "lodash";
const a = { x: 0, y: { z: (a, b) => a + b } };
const b = cloneDeep(a);
console.log(b.y.z(1, 2)); // returns 3
Using Object.create() does create a new object. The properties are shared between objects (changing one also changes the other). The difference with a normal copy, is that properties are added under the new object's prototype __proto__. When you never change the original object, this could also work as a shallow copy, but I would suggest using one of the methods above, unless you specifically need this behaviour.
Try using the create() method like as mentioned below.
var tempMyObj = Object.create(myObj);
This will solve the issue.
Try using $.extend():
If, however, you want to preserve both of the original objects, you
can do so by passing an empty object as the target:
var object = $.extend({}, object1, object2);
var tempMyObj = $.extend({}, myObj);
use three dots to spread object in the new variable
const a = {b: 1, c: 0};
let d = {...a};
As I couldn't find this code anywhere around suggested answers for shallow copy/cloning cases, I'll leave this here:
// shortcuts
const {
create,
getOwnPropertyDescriptors,
getPrototypeOf
} = Object;
// utility
const shallowClone = source => create(
getPrototypeOf(source),
getOwnPropertyDescriptors(source)
);
// ... everyday code ...
const first = {
_counts: 0,
get count() {
return ++this._counts;
}
};
first.count; // 1
const second = shallowClone(first);
// all accessors are preserved
second.count; // 2
second.count; // 3
second.count; // 4
// but `first` is still where it was
first.count; // just 2
The main difference compared to Object.assign or {...spread} operations, is that this utility will preserve all accessors, symbols, and so on, in the process, including the inheritance.
Every other solution in this space seems to miss the fact cloning, or even copying, is not just about properties values as retrieved once, but accessors and inheritance might be more than welcome in daily cases.
For everything else, use native structuredClone method or its polyfill 👋
This might be very tricky, let me try to put this in a simple way. When you "copy" one variable to another variable in javascript, you are not actually copying its value from one to another, you are assigning to the copied variable, a reference to the original object. To actually make a copy, you need to create a new object use
The tricky part is because there's a difference between assigning a new value to the copied variable and modify its value. When you assign a new value to the copy variable, you are getting rid of the reference and assigning the new value to the copy, however, if you only modify the value of the copy (without assigning a new value), you are modifying the copy and the original.
Hope the example helps!
let original = "Apple";
let copy1 = copy2 = original;
copy1 = "Banana";
copy2 = "John";
console.log("ASSIGNING a new value to a copied variable only changes the copy. The ogirinal variable doesn't change");
console.log(original); // Apple
console.log(copy1); // Banana
console.log(copy2); // John
//----------------------------
original = { "fruit" : "Apple" };
copy1 = copy2 = original;
copy1 = {"animal" : "Dog"};
copy2 = "John";
console.log("\n ASSIGNING a new value to a copied variable only changes the copy. The ogirinal variable doesn't change");
console.log(original); //{ fruit: 'Apple' }
console.log(copy1); // { animal: 'Dog' }
console.log(copy2); // John */
//----------------------------
// HERE'S THE TRICK!!!!!!!
original = { "fruit" : "Apple" };
let real_copy = {};
Object.assign(real_copy, original);
copy1 = copy2 = original;
copy1["fruit"] = "Banana"; // we're not assiging a new value to the variable, we're only MODIFYING it, so it changes the copy and the original!!!!
copy2 = "John";
console.log("\n MODIFY the variable without assigning a new value to it, also changes the original variable")
console.log(original); //{ fruit: 'Banana' } <====== Ops!!!!!!
console.log(copy1); // { fruit: 'Banana' }
console.log(copy2); // John
console.log(real_copy); // { fruit: 'Apple' } <======== real copy!
If you have the same problem with arrays then here is the solution
let sectionlist = [{"name":"xyz"},{"name":"abc"}];
let mainsectionlist = [];
for (let i = 0; i < sectionlist.length; i++) {
mainsectionlist[i] = Object.assign({}, sectionlist[i]);
}
In Javascript objects are passed as reference and they using shallow comparison so when we change any instance of the object the same changes is also referenced to the main object.
To ignore this replication we can stringify the JSON object.
example :-
let obj = {
key: "value"
}
function convertObj(obj){
let newObj = JSON.parse(obj);
console.log(newObj)
}
convertObj(JSON.stringify(obj));
The following would copy objA to objB without referencing objA
let objA = { prop: 1 },
let objB = Object.assign( {}, objA )
objB.prop = 2;
console.log( objA , objB )
You can now use structuredClone() for deep object clones :
https://developer.mozilla.org/en-US/docs/Web/API/structuredClone
const newItem = structuredClone(oldItem);
Serialize the original object into JSON and Deserialize to another object variable of same type. This will give you copy of object with all property values. And any modification to original object will not impact the copied object.
string s = Serialize(object); //Serialize to JSON
//Deserialize to original object type
tempSearchRequest = JsonConvert.DeserializeObject<OriginalObjectType>(s);
I'm sure there is a simple way to do this, but am stumped for now.
I have many variables defined at the top of my script (here is an example of two):
var firstVar,secondVar;
Then I have an object which contains those variables:
var myObj = { a: {name:firstVar, number:1}, b: {name:secondVar, number:2}
I want to assign values to those variables:
keys = Object.keys(myObj);
function getAll(e){
var myArray = [];
for (var prop in myObj){
myArray.push(myObj.prop[e]);
}
return myArray;
}
The behaviour I want is:
var nameVars = getAll(name);
// [firstVar,secondVar]
But instead it returns:
// [undefined,undefined]
How else can I get the variables before defining them?
Then I have an object which contains those variables:
No, it doesn't. It contains a copy of the value those variables contained as of when you created the object (which is undefined, since you've never assigned a value to them). Once created, there is no ongoing link between the object property you've copied the value to and the variable.
Since the object has no enduring link to the variables, there's no way for getAll to return the information you've said you want.
You've said in a comment that you're building d3 graphs and have the same structure with some variables, and want to avoid repeating yourself. It sounds to me like you want a builder function:
function buildObject(firstVar, secondVar) {
return { a: {name:firstVar, number:1}, b: {name:secondVar, number:2} };
}
...which you would then use like this:
var obj1 = buildObject("value1", "value2");
// do a graph
var obj2 = buildObject("valueA", "valueB");
// do a graph
...or possibly even something that just takes the variables and produces the graph:
function makeGraph(firstVar, secondVar) {
buildTheGraph({ a: {name:firstVar, number:1}, b: {name:secondVar, number:2} });
}
I don't think it is, but if it's the names you want, just put them in quotes (and also myArray.push(myObj.prop[e]); should be myArray.push(myObj[prop][e]); and getAll(name) should be getAll("name")), but again there's no link to the variables at all:
// Since they're not used, we don't even need these: var firstVar, secondVar;
var myObj = { a: { name: "firstVar", number: 1 }, b: { name: "secondVar", number: 2 } };
function getAll(e) {
var myArray = [];
for (var prop in myObj) {
myArray.push(myObj[prop][e]);
}
return myArray;
}
var nameVars = getAll("name");
console.log(nameVars);
...but note that having the names doesn't help you get the variable values later (unless you use eval, which you should seek to avoid).
Consider the following:
var obj1 = {"value":"one"};
var obj2 = obj1;
console.log(obj2.value+"\n"); // prints "one"
obj1 = {"value":"two"};
console.log(obj2.value+"\n"); // still prints "one"
I understand the reason for this, in the first two lines, obj1 and obj2 are references which both point to the same object, {"value":"one"}, somewhere in memory. When obj1 is assigned to a different object, {"value":"two"}, obj2 is still pointing to the same object {"value":"one"} in memory.
What I am looking for is a way to coerce the {"value":"one"} object in memory to "redirect" its callers to the {"value":"two"} object. In other words, I am looking for a way to manipulate the {"value":"one"} object so that the obj2 variable would ultimately point to the {"value":"two"} object, without reassigning the obj2 variable:
var obj1 = {"value":"one"};
var obj2 = obj1;
console.log(obj2.value+"\n"); // prints "one"
// ...some code to manipulate the `{"value":"one"}` object in memory
// so that *any* references which originally pointed to the
// `{"value":"one"}` object now point to the `{"value":"two"}`
// object, like a sort of "redirection". This would be done
// without ever explicitly reassigning the references.
console.log(obj2.value+"\n"); // now prints "two"
Is there a way to accomplish this?
The actual application involves some pretty complex Mozilla code which would encumber this thread to try and explain, so I am asking this as a general theory question.
EDIT: CONCLUSION:
"No" is the most correct answer to the actual question, torazaburo's comment below states this well. However I felt that Patrick's answer, using a proxy, comes the closest to accomplishing this, so I accepted his answer. I will add that while proxies are very powerful tools, they are not the same as the actual target object, and there are some limitations.
Check out proxies. You could use the get and set to dynamically reference a base object of your choosing, exposing proxies as the free-floating references you want to implicitly update. Here's an example:
function Proxyable(target) {
this.target = target;
this.proxy = new Proxy(this, Proxyable.handler);
}
Proxyable.prototype.getReference = function () {
return this.proxy;
};
Proxyable.prototype.setReference = function (target) {
this.target = target;
};
Proxyable.handler = {
get: function (proxyable, property) {
return proxyable.target[property];
},
set: function (proxyable, property, value) {
return proxyable.target[property] = value;
}
};
// original object
var original = { value: ['one'] };
// have to create a namespace unfortunately
var nsp = new Proxyable(original);
// reference the ref value of the namespace
var ref1 = nsp.getReference();
var ref2 = nsp.getReference();
// same references (not just values)
console.log(ref1.value === original.value);
console.log(ref2.value === original.value);
// hot-load a replacement object over the original
var replacement = { value: ['two'] };
// into the namespace
nsp.setReference(replacement);
// old references broken
console.log(ref1.value !== original.value);
console.log(ref2.value !== original.value);
// new references in place
console.log(ref1.value === replacement.value);
console.log(ref2.value === replacement.value);
I think this answer will guide you in the best way to handle this behavior. It's not possible to simply redirect an object to another object, but you can simply modify its values so that it matches the object you're trying to change.
You could also define a global object:
var objs = {
1: {value: 'test'}
2: {value: 'test2'}
};
And from there, pass around an object with the value of the key you're trying to mock. Simply change the key, and then refer to the new element.
An example:
var obj = {key: 1};
console.log(objs[obj.key]);
//Outputs: {value: 'test'}
obj.key = 2;
console.log(objs[obj.key]);
//Outputs: {value: 'test2'}
There's no way directly to do what you want. For the very reason you've stated in your question - that's just how variables and values work in javascript.
However, your very own words in your question hints at a way to achieve something that may work. But depending on the code you're dealing with it may not be what you want.
You can simply wrap the object in another reference. So that changing the content of the reference changes the object pointed to by all variables sharing the reference. You may use either of the two reference containers available: objects or arrays:
// This works:
var obj1 = [{value:'one'}];
var obj2 = obj1;
var obj1[0] = {value:'two'};
console.log(obj1[0]); // prints {"value":"two"}
console.log(obj2[0]); // prints {"value":"two"}
Alternatively:
// This also works:
var obj1 = {obj:{value:'one'}};
var obj2 = obj1;
var obj1.obj = {value:'two'};
console.log(obj1.obj); // prints {"value":"two"}
console.log(obj2.obj); // prints {"value":"two"}
I am copying objA to objB
const objA = { prop: 1 },
const objB = objA;
objB.prop = 2;
console.log(objA.prop); // logs 2 instead of 1
same problem for Arrays
const arrA = [1, 2, 3],
const arrB = arrA;
arrB.push(4);
console.log(arrA.length); // `arrA` has 4 elements instead of 3.
It is clear that you have some misconceptions of what the statement var tempMyObj = myObj; does.
In JavaScript objects are passed and assigned by reference (more accurately the value of a reference), so tempMyObj and myObj are both references to the same object.
Here is a simplified illustration that may help you visualize what is happening
// [Object1]<--------- myObj
var tempMyObj = myObj;
// [Object1]<--------- myObj
// ^
// |
// ----------- tempMyObj
As you can see after the assignment, both references are pointing to the same object.
You need to create a copy if you need to modify one and not the other.
// [Object1]<--------- myObj
const tempMyObj = Object.assign({}, myObj);
// [Object1]<--------- myObj
// [Object2]<--------- tempMyObj
Old Answer:
Here are a couple of other ways of creating a copy of an object
Since you are already using jQuery:
var newObject = jQuery.extend(true, {}, myObj);
With vanilla JavaScript
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var newObject = clone(myObj);
See here and here
deep clone object with JSON.parse() and JSON.stringify
// Deep Clone
obj = { a: 0 , b: { c: 0}};
let deepClone = JSON.parse(JSON.stringify(obj));
refrence: this article
Better reference: this article
To sum it all up, and for clarification, there's four ways of copying a JS object.
A normal copy. When you change the original object's properties, the copied object's properties will change too (and vice versa).
const a = { x: 0}
const b = a;
b.x = 1; // also updates a.x
A shallow copy. Top level properties will be unique for the original and the copied object. Nested properties will be shared across both objects though. Use the spread operator ...{} or Object.assign().
const a = { x: 0, y: { z: 0 } };
const b = {...a}; // or const b = Object.assign({}, a);
b.x = 1; // doesn't update a.x
b.y.z = 1; // also updates a.y.z
A deep copy. All properties are unique for the original and the copied object, even nested properties. For a deep copy, serialize the object to JSON and parse it back to a JS object.
const a = { x: 0, y: { z: 0 } };
const b = JSON.parse(JSON.stringify(a));
b.y.z = 1; // doesn't update a.y.z
A full deep copy. With the above technique, property values that are not valid in JSON (like functions) will be discarded. If you need a deep copy and keep nested properties that contain functions, you might want to look into a utility library like lodash.
import { cloneDeep } from "lodash";
const a = { x: 0, y: { z: (a, b) => a + b } };
const b = cloneDeep(a);
console.log(b.y.z(1, 2)); // returns 3
Using Object.create() does create a new object. The properties are shared between objects (changing one also changes the other). The difference with a normal copy, is that properties are added under the new object's prototype __proto__. When you never change the original object, this could also work as a shallow copy, but I would suggest using one of the methods above, unless you specifically need this behaviour.
Try using the create() method like as mentioned below.
var tempMyObj = Object.create(myObj);
This will solve the issue.
Try using $.extend():
If, however, you want to preserve both of the original objects, you
can do so by passing an empty object as the target:
var object = $.extend({}, object1, object2);
var tempMyObj = $.extend({}, myObj);
use three dots to spread object in the new variable
const a = {b: 1, c: 0};
let d = {...a};
As I couldn't find this code anywhere around suggested answers for shallow copy/cloning cases, I'll leave this here:
// shortcuts
const {
create,
getOwnPropertyDescriptors,
getPrototypeOf
} = Object;
// utility
const shallowClone = source => create(
getPrototypeOf(source),
getOwnPropertyDescriptors(source)
);
// ... everyday code ...
const first = {
_counts: 0,
get count() {
return ++this._counts;
}
};
first.count; // 1
const second = shallowClone(first);
// all accessors are preserved
second.count; // 2
second.count; // 3
second.count; // 4
// but `first` is still where it was
first.count; // just 2
The main difference compared to Object.assign or {...spread} operations, is that this utility will preserve all accessors, symbols, and so on, in the process, including the inheritance.
Every other solution in this space seems to miss the fact cloning, or even copying, is not just about properties values as retrieved once, but accessors and inheritance might be more than welcome in daily cases.
For everything else, use native structuredClone method or its polyfill 👋
This might be very tricky, let me try to put this in a simple way. When you "copy" one variable to another variable in javascript, you are not actually copying its value from one to another, you are assigning to the copied variable, a reference to the original object. To actually make a copy, you need to create a new object use
The tricky part is because there's a difference between assigning a new value to the copied variable and modify its value. When you assign a new value to the copy variable, you are getting rid of the reference and assigning the new value to the copy, however, if you only modify the value of the copy (without assigning a new value), you are modifying the copy and the original.
Hope the example helps!
let original = "Apple";
let copy1 = copy2 = original;
copy1 = "Banana";
copy2 = "John";
console.log("ASSIGNING a new value to a copied variable only changes the copy. The ogirinal variable doesn't change");
console.log(original); // Apple
console.log(copy1); // Banana
console.log(copy2); // John
//----------------------------
original = { "fruit" : "Apple" };
copy1 = copy2 = original;
copy1 = {"animal" : "Dog"};
copy2 = "John";
console.log("\n ASSIGNING a new value to a copied variable only changes the copy. The ogirinal variable doesn't change");
console.log(original); //{ fruit: 'Apple' }
console.log(copy1); // { animal: 'Dog' }
console.log(copy2); // John */
//----------------------------
// HERE'S THE TRICK!!!!!!!
original = { "fruit" : "Apple" };
let real_copy = {};
Object.assign(real_copy, original);
copy1 = copy2 = original;
copy1["fruit"] = "Banana"; // we're not assiging a new value to the variable, we're only MODIFYING it, so it changes the copy and the original!!!!
copy2 = "John";
console.log("\n MODIFY the variable without assigning a new value to it, also changes the original variable")
console.log(original); //{ fruit: 'Banana' } <====== Ops!!!!!!
console.log(copy1); // { fruit: 'Banana' }
console.log(copy2); // John
console.log(real_copy); // { fruit: 'Apple' } <======== real copy!
If you have the same problem with arrays then here is the solution
let sectionlist = [{"name":"xyz"},{"name":"abc"}];
let mainsectionlist = [];
for (let i = 0; i < sectionlist.length; i++) {
mainsectionlist[i] = Object.assign({}, sectionlist[i]);
}
In Javascript objects are passed as reference and they using shallow comparison so when we change any instance of the object the same changes is also referenced to the main object.
To ignore this replication we can stringify the JSON object.
example :-
let obj = {
key: "value"
}
function convertObj(obj){
let newObj = JSON.parse(obj);
console.log(newObj)
}
convertObj(JSON.stringify(obj));
The following would copy objA to objB without referencing objA
let objA = { prop: 1 },
let objB = Object.assign( {}, objA )
objB.prop = 2;
console.log( objA , objB )
You can now use structuredClone() for deep object clones :
https://developer.mozilla.org/en-US/docs/Web/API/structuredClone
const newItem = structuredClone(oldItem);
Serialize the original object into JSON and Deserialize to another object variable of same type. This will give you copy of object with all property values. And any modification to original object will not impact the copied object.
string s = Serialize(object); //Serialize to JSON
//Deserialize to original object type
tempSearchRequest = JsonConvert.DeserializeObject<OriginalObjectType>(s);