Add new attribute (element) to JSON object using JavaScript

Add new attribute (element) to JSON object using JavaScript

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 = 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 = {
            host: "hostName",
                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 ;



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:

With ECMAScript 2015 you can use Spread Syntax (… three dots):

let  people = {id: 4 ,firstName: 'John'};
people = {...people, secondName:'Forget'};

It’s allow you to add sub objects:

people = {...people, city:{estate: 'Alabama'}};

the result would be:


You also can merge objects:

var mergedObj = { ...obj1, ...obj2 };

Solution 6:

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.