Add new attribute (element) to JSON object using JavaScript
JSON stands for JavaScript Object Notation. A JSON object is really a string that has yet to be turned into the object it represents.
To add a property to an existing object in JS you could do the following.
object["property"] = value;
or
object.property = value;
If you provide some extra info like exactly what you need to do in context you might get a more tailored answer.
var jsonObj = { members: { host: "hostName", viewers: { user1: "value1", user2: "value2", user3: "value3" } }}var i;for(i=4; i<=8; i++){ var newUser = "user" + i; var newValue = "value" + i; jsonObj.members.viewers[newUser] = newValue ;}console.log(jsonObj);
A JSON object is simply a javascript object, so with Javascript being a prototype based language, all you have to do is address it using the dot notation.
mything.NewField = 'foo';