Updating object property, initially set to an undefined array element - 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() ?

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);

Assuming you want the value of obj.x as a primitive :
It's not possible to assign the reference of a var to obj.x.You can make obj.x as a function that'll get the latest value of that variable
var variable= 2
var obj = {
x: function() {
return variable;
},
y: 'hello'
};
variable = 5;
console.log(obj.x()); //prints 5

Javascript objects are not reinitialised by reference.
You need to do obj.x = 1 to update the object.

Related

Javascript dynamic nested objects

I was looking into how to create a dynamic nested objects from a string, for example, a string "obj1.obj2.obj3.obj4", how do you turn that into nested objects with the same order.
I googled around and i found this nice and clean code, but i did not understand how it worked, and there was no explanation on the page where it was written, can someone explain how this works please?
here is the code:
var s = "key1.key2.key3.key4";
var a = s.split('.');
var obj = {};
var temp = obj;
for (var k =0; k < a.length; k++) {
temp = temp[a[k]] = {};
console.log(temp);
}
console.log(obj);
why is there a var temp = obj?
what does this line do?:
temp = temp[a[k]] = {};
also, the console.log(temp) inside the loop always logs an empty object {}, why?
Thanks for the feedback!
why is there a var temp = obj?
obj is a variable to hold the completed object. temp is a variable to hold each intermediate step of the object being built. temp starts out with the same value as obj so that the first iteration of the loop adds on to obj.
what does this line do?:
temp = temp[a[k]] = {};
Assign an empty object to a property in temp with the name a[k], where a[k] is one of the values in a.
Assign that new empty object to temp.
This could be written separately as two lines:
temp[a[k]] = {};
temp = temp[a[k]];
also, the console.log(temp) inside the loop always logs an empty object {}, why?
Because the previous line assigns an empty object to temp.
Your question boils down to this (comments inline)
var x = {};
var y = x;
y[ "a" ] = {}; //reference to x stays so x also becomes { "a": {} }
y = y["a"]; //now y effectively becomes {} but has the same reference to y["a"] as assignment works right to left hence property `a` is becomes non-enumerable and hence shadowed.
console.log( "First Run" );
console.log( y ); //prints {}
console.log( x ); //prints { "a": {} }
y[ "a" ] = {}; //y still has a non-enumerable property `a`
y = y["a"]; //same as above y = y["a"], y again becomes {}
console.log( "Second Run" );
console.log( y ); //prints {} again
console.log( x ); //prints { "a": { "a": {} } }
Outputs
First Run
{}
{ "a": {} }
Second Run
{}
{ "a": {
"a": {} } }
Have added comments in code, hope it will be useful
var s = "key1.key2.key3.key4";
//split the string by dot(.) and create an array
var a = s.split('.');
//Creating an empty object
var obj = {};
var temp = obj;
//looping over the array
for (var k = 0; k < a.length; k++) {
//a[k] will be key1,key2,key3....
// temp is an object,square bracket is use to create a object key
// using a variable name
// variable name here is key1,key2....
//temp[a[k]] will initialize an empty object
temp = temp[a[k]] = {};
console.log(temp);
}
console.log(obj);
It seems where you are iterating the array, in that temp object is newly creating and assigning key to obj.
temp = temp[a[k]] = {};
above line simply assigns a[index] value as a key to the new object and as a reference to obj the nested object is created.
for your question,
why is there a var temp = obj?
it copies obj object into temp variable
also, the console.log(temp) inside the loop always logs an empty object {}, why?
since you are recreating an empty object (or reassigning).

what will be the output of the java script code?

var a = {};
b = {x:4};
c = {y: 2};
a[b] = 123;
a[c] = 456;
console.log(a[b]);
I was thinking, output should be 123 but not, I do not know..
what will be the output and explain with reason
The output will be 456
// It creates an empty object
var a = {};
b = {
x: 4
}; // b become a new object
c = {
y: 2
}; // c become a new object
/**Next line trying to create a key in object a which will look like {x:4}
which is invalid so it will look like {[object Object]} and its value will be 123**/
a[b] = 123;
/**Same operation with following line and its value will be 456.
In this case the previous[object Object] will be over written by
new one so both occupy the same key and hence 123 is overwritten 456**/
a[c] = 456;

Javascript - Get the associative array key value

I have an object with one key value as given below -
var a = {};
a.x = "randomvalue";
My requirement is to get access the value "randomvalue", but the catch is I dont know that the property name is "x".
Simplest way to get the value??
Try:
var v, i;
var a = {};
a.x = "randomvalue";
for (x in a) {
if a[x] === "randomvalue" {
v = x;
i = "randomvalue";
}
}
Then v contains the object key and i contains the object value (although you don't really need it).
Or, if you know the value index:
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

setting value for array object via index sets all array items

I have a complex javascript object with an array. When I try to set the value for one attribute of an index, it's applied to all items of the array.
Here is a basic example:
var obj = new Object();
obj.arr = [];
obj.arr[0] = {pos:[0,0]};
obj.arr[1] = {pos:[0,0]};
Now if i set a value for an attribute of the object, via a specific index,
obj.arr[0].pos = [10,10];
obj.arr[1].pos = [5,5];
Here it seems to be setting the value [5,5] for both items of the array. The resulting values are:
console.log(obj.arr[0].pos) returns [5,5]
and
console.log(obj.arr[1].pos) also returns [5,5]
My actual object is far more complex, but this is the basic idea of what's happening...
Any ideas?
They share the same link, i.e. several variables/properties of an object are referring to the same value.
Exact answer (where's the error) depends on how your object is composed.
var nested = {a:1};
var obj = {arr:[]};
obj.arr[0] = {pos:0, n:nested};
obj.arr[1] = {pos:0, n:nested};
obj.arr[0].pos = 1;
obj.arr[1].pos == 1; // false
obj.arr[0].nested.a = 2;
obj.arr[1].nested.a == 2; // true
Assignment of the same array/object literals is not the same.
var a = [0];
var b = [0];
b[0] = 1;
a[0] == 1; // false
b = a;
a[0] = 2;
b[0] == 2; // true
a = b = [0];
a[0] = 1;
b[0] == 1; // true

javascript array index problem!

var a = new array();
a[1] = 'A';
b[10] = 'B';
console.log(a);
/[undefined, "A", undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, "B"]/
I want to remove undefined element
but what is the process??
First of all, jQuery has nothing to do with this.
Second, arrays are "autofilled". If you define index 10, all indexes 0 - 9 will be occupied automatically, that's just the way Javascript arrays work.
What you're looking for is probably an object:
var a = {};
a[1] = 'A';
a[10] = 'B';
or
var a = {
1 : 'A',
10 : 'B'
};
In this case you can use an Object instead of an Array like so:
var a = {}; // or var a = new Object();
a[1] = 'A';
a[10] = 'B';
a['foo'] = 'bar';
a.bar = 'foo'; // same as a['bar'] = 'foo';
console.log(a);
Arrays always start at 0 and then go up to the last filled index.
You could use an object to solve your problem:
var a = {};
a[1] = 'A';
a[10] = 'B';
well, to remove those undefined parts do
a[0] = 'A';
a[1] = 'B';
In your snippet, you fill the element with index 10 which forces the ECMAscript to create an array with 10 fields. There are no definitions for all that fields between 1 and 10, which means those are correctly undefined.
To remove that fields you either have to set a proper value or map the non-undefined values into a new array which would just be unnecesarry if you create a correct array in the first place.
Create an true object instead of an array (which actually also is an object) to have your desired behavior.
var a = {};
a[1] = 'A';
a[2] = 'B';
console.log(a);

Categories

Resources