I have a 'trades' object that includes a reference to orderBook.BTCUSDT. My intention is to change 'trades' when orderBook.BTCUSDT is changed.
However, changing orderBook.BTCUSDT does not work. But changing orderBook.BTCUSDT.asks does.
Why?
orderBook = {'BTCUSDT': {'asks':[1,2,3,5], 'bids':[6,7,8,9]}};
trades = {"one": orderBook.BTCUSDT};
orderBook.BTCUSDT = 1234; // does not work
console.log(trades);
/* Output:
{
"one": {
"asks": [
1,
2,
3,
5
],
"bids": [
6,
7,
8,
9
]
}
}
*/
orderBook = {'BTCUSDT': {'asks':[1,2,3,5], 'bids':[6,7,8,9]}};
trades = {"one": orderBook.BTCUSDT};
orderBook.BTCUSDT.asks = 1234; // works
console.log(trades);
/* Output:
{
"one": {
"asks": 1234,
"bids": [
6,
7,
8,
9
]
}
}
*/
Edit after Axiac and Artur responses
After reading responses from Axiac and Artur, I found another way to ask the question. Why does the first code block work but not the second? Why should I have to add another level to the object by using 'prices'? Seems like both are trying to do the same thing (replace an object with another object but keep the reference), just at different levels.
orderBook = {BTCUSDT: { prices: {'asks':[1,2,3,5], 'bids':[6,7,8,9]}}};
trades = {one: orderBook.BTCUSDT};
orderBook.BTCUSDT.prices = {'asks':[11,12,13,15], 'bids':[16,17,18,19]}; // trades.one.BTCUSDT.prices is updated as expected
console.log(trades);
orderBook = {BTCUSDT: {'asks':[1,2,3,5], 'bids':[6,7,8,9]}};
trades = {one: orderBook.BTCUSDT};
orderBook.BTCUSDT = {'asks':[11,12,13,15], 'bids':[16,17,18,19]}; // trades.one.BTCUSDT is NOT updated as expected
console.log(trades);
EDIT: Mutation vs Reassignment
I believe I found the answer inside this post.
In both code blocks above, trades.one is set to orderBook.BTCUSDT.
In the second code block, orderBook.BTCUSDT is being reassigned with the third line whereas in the first code block orderBook.BTCUSDT is being mutated in the third line. Changing orderBook.BTCUSDT.prices is a mutation so the reference is not lost. However, with the second code block, the reassignment breaks the reference.
This is what axiac and Artur were also saying without explicitly discussing mutation VS reassignment.