Tutorial :Add new attribute (element) to JSON object using JavaScript



Question:

How do I add new attribute (element) to JSON object using JavaScript?


Solution:1

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.


Solution:2

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


Solution:3

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


Solution:4

thanks for this post. I want to add something that can be useful.

For IE, it is good to use

object["property"] = value;  

syntax because some special words in IE can give you an error.

An example:

object.class = 'value';  

this fails in IE, because "class" is a special word. I spent several hours with this.


Solution:5

You can also use Object.assign from ECMAScript 2015. It also allows you to add nested attributes at once. E.g.:

const myObject = {};    Object.assign(myObject, {      firstNewAttribute: {          nestedAttribute: 'woohoo!'      }  });  

Ps: This will not override the existing object with the assigned attributes. Instead they'll be added. However if you assign a value to an existing attribute then it would be overridden.


Solution:6

extend: function(){      if(arguments.length === 0){ return; }      var x = arguments.length === 1 ? this : arguments[0];      var y;        for(var i = 1, len = arguments.length; i < len; i++) {          y = arguments[i];          for(var key in y){              if(!(y[key] instanceof Function)){                  x[key] = y[key];              }          }                 };        return x;  }  

Extends multiple json objects (ignores functions):

extend({obj: 'hej'}, {obj2: 'helo'}, {obj3: {objinside: 'yes'}});  

Will result in a single json object


Solution:7

You can also add new json objects into your json, using the extend function,

var newJson = $.extend({}, {my:"json"}, {other:"json"});  // result -> {my: "json", other: "json"}  

A very good option for the extend function is the recursive merge. Just add the true value as the first parameter (read the documentation for more options). Example,

var newJson = $.extend(true, {}, {      my:"json",      nestedJson: {a1:1, a2:2}  }, {      other:"json",      nestedJson: {b1:1, b2:2}  });  // result -> {my: "json", other: "json", nestedJson: {a1:1, a2:2, b1:1, b2:2}}  


Solution:8

Uses $.extend() of jquery, like this:

token = {_token:window.Laravel.csrfToken};  data = {v1:'asdass',v2:'sdfsdf'}  dat = $.extend(token,data);   

I hope you serve them.


Solution:9

for(var i=0;i<JsonObject.length;i++){                      alert("inside forloop");                      var dataArray = JsonObject[i];                      alert(dataArray["data"]);                }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »