Consider the following :
let data = {
"world": "bc",
"d": "ef",
"g": "hi",
};
let panel = {
"hello": {
"world": {},
}
};
let dataTree = panel.hello;
let exampleBool = true;
if (exampleBool) {
dataTree = panel.hello.world;
}
Object.assign(dataTree, data);
dataTree.world = "xz";
console.log(dataTree.world);
console.log(data.world);
console.log(data === dataTree);
Output :
xz
bc
false
Desired output :
xz
xz
true
I would like to set a value to the object property referenced by dataTree, which can change depending on exampleBool.
I would like to link the object referenced by data be the same as dataTree, in other word makes dataTree === data to be true.
The problem with Object.assign is that it makes a copy of each property in data and in my case, data keys can be a thousands length so I don't want to clone each ones.
Any way to do this in JS ?
I would like to set a value to the object property referenced by
dataTree
The variable dataTree is not a reference to an object property. There is no such thing in JS. dataTree does reference the { "world": {} } object (or, after the conditional assignment, the {} object), and that's it. You cannot mutate the property where you get the object from through the variable.
Instead, store the base object and the property name:
let data = {
"world": "bc",
"d": "ef",
"g": "hi",
};
let panel = {
"hello": {
"world": {},
}
};
let dataTreeBase = panel,
dataTreeProp = "hello";
let exampleBool = true;
if (exampleBool) {
dataTreeBase = panel.hello;
dataTreeProp = "world";
}
dataTreeBase[dataTreeProp] = data;
dataTreeBase[dataTreeProp].world = "xz";
console.log(dataTreeBase[dataTreeProp].world);
console.log(data.world);
console.log(data === dataTreeBase[dataTreeProp]);
Of course there are various ways to abstract this in functions or objects with getters/setters or methods, but you cannot achieve this with just a plain variable.
You can assign dataTree to data:
let data = {
"world": "bc",
"d": "ef",
"g": "hi",
};
let panel = {
"hello": {
"world": {},
}
};
let dataTree = panel.hello;
let exampleBool = true;
if (exampleBool) {
dataTree = panel.hello.world;
}
data = dataTree;
dataTree.world = "xz";
console.log(dataTree.world);
console.log(data.world);
console.log(data === dataTree);