简体   繁体   中英

How can I dynamically add to this object

I have the object msg.data which holds:

{    
"user_id": 1,
"success": "true"
}

I would like to add name to this list:

{    
"user_id": 1,
"success": "true",
"name" : "giri"
}

I have tried:

msg.data.name = "giri";

but when I print out msg.data , I always get the initial result.

Would someone know the correct way to do this?

I just tried this in the console, and it works for me:

msg = {};
msg.data = {    
"user_id": 1,
"success": "true"
};
msg.data.name = "giri";
msg; //Since we're in the console, this will output the variable. Otherwise use console.log(msg) to output the contents.

Ensure you have no typos, and nothing else is modifying the object. Do a console.dir before and right after your statement. Also, be aware that the console may display the incorrect object at the time (If you use console.log ), since it's showing you the current object by reference (Which may be different at the time you view the console). You can read this post for a bit more information on this.

Depending upon typeof msg.data . If it is an object, then it should be straightforward to add newer members using . You can add name property as follows

msg.data.name = "haseeb";

if it is a json string then you need to parse it into and object and then add property using .

var myobject = JSON.parse(msg.data);
myobject.name = "haseeb";

if you are using

msg = {}; or msg.data = {} it works as an object

and you can add any variable dynamicly

msg.firstvar=""
msg.Secondvar=""
msg.Thirdvar=""

msg.data.firstvar=""
msg.data.Secondvar=""
msg.data.Thirdvar=""

Here is a simple way to do it,

I assume the variable be a dymanic object created, a response on ajax

var msg = {
    "user_id" : 1,
    "success" : true
};

if (msg.name == undefined ) {

    Object.defineProperty(msg, 'name', {
        value : 'giri',
        writable : false, // if you want the value to be change
        enumerable : true // if you want the object to property to be iterated
    });
}

Read also Object Define Property

but when I print out msg.data, I always get the initial result.

Means that msg.data doesn't actually exist, it yields "undefined" (most likely).

Use debugger (or print out in console) the contents of msg.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM