Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating object property, initially set to an undefined array element

Tags:

javascript

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() ?

like image 230
Kaya Toast Avatar asked Jan 06 '23 20:01

Kaya Toast


2 Answers

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));
like image 80
AtheistP3ace Avatar answered Jan 26 '23 23:01

AtheistP3ace


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);
like image 29
Lewis Avatar answered Jan 26 '23 22:01

Lewis