Dharan
Dharan

Reputation: 262

assign property value by another property and change property value

assign property value by another property and change it dynamically

     var obj = {
          name : null,
          id : null
       };

    var result = obj.name;
   console.log(result); // null

   obj.name = 'myName'
   console.log(result); // null 
  // here i want to show 'myname'

Upvotes: 1

Views: 237

Answers (2)

random
random

Reputation: 7891

In result, store the reference of obj instead of storing the value of obj.name. Your code var result = obj.name store the value null and is not a reference to object.

var obj = {
    name : null,
    id : null
};

var result = obj;
console.log(result); // null

obj.name = 'myName'
console.log(result); 

console.log(result.name);

You can also first change the obj name property and then assign it's value to your result, so that changed property value gets reflected.

var obj = {
    name : null,
    id : null
};

obj.name = 'myName';

var result = obj.name;

console.log(result); 

Upvotes: 1

Danyal Imran
Danyal Imran

Reputation: 2605

obj.name is a primitive value, therefore the change to obj.name doesn't modify the result

You could set the result to be a reference for obj changes to have an effect on the result

var obj = {
    name : null,
    id : null
};

var result = obj; // create reference
obj.name = 'hi';  // modify original object

console.log(result.name);

Upvotes: 0

Related Questions