var A = [];
var obj = {
    x: A[1],
    y: 'hello'
};
A[1] = 1;
console.log(JSON.stringify(obj)); // {"y":"hello"}
By the time I'm using obj in console.log(), A[1] has already been defined. 
How can I get the "latest" obj, with all its properties updated ? Such that we get {"x":1,"y":"hello"} when we do console.log() ?
You are getting the latest object. If you want the x property to update as its assigned value changes throughout the runtime of the code you need to use an object, since it will just store a reference to it and as the place in memory changes you will see those changes everywhere you assigned it. Arrays are considered objects so you could just assign A to x.
var A = [];
var obj = {
    x: A,
    y: 'hello'
};
A[1] = 1;
alert(JSON.stringify(obj));
Another example using an object as value:
var A = [];
var B = {};
A[1] = B;
var obj = {
    x: A[1],
    y: 'hello'
};
B.z = 1;
alert(JSON.stringify(obj));
                        A[1] = 1; is actually defined when obj was already constructed. So obj.x is always undefined.
var A = [];
A[1] = 1;
var obj = {
  x: A[1],
  y: 'hello'
};
document.body.textContent = JSON.stringify(obj);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With