565

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

bluish
  • 26,356
  • 27
  • 122
  • 180

11 Answers11

740

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.

Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
  • is this possible then: object["property"]["subProperty"]... that would be amazing. Just tried. var a.s = "what"; a.s.d = "nope"; It's undefined :( – shanehoban May 27 '14 at 13:16
  • 6
    @shanehoban here `a` is JSON, `a.s` as just defined by you is a string. Now you are trying to add `["subproperty"]` to a string. Do you understand now why u got the error? – shivam Jul 12 '14 at 11:45
  • 3
    For beginners, remember that as Quintin says, a JSON "object" is not an object at all, it's just a string. You would need to convert it to an actual Javascript object with JSON.parse() before using his example of `object["property"] = value;` – SpaceNinja Dec 28 '15 at 20:02
  • 2
    @shanehoban check my answer on the top and you'll see how you can add multiple attributes at once. – Victor Augusto Aug 24 '17 at 12:57
  • For a newbie like me, it is worth mentioning that object declaration should be like var j = {}. Above assignment will not work if object is declared as var j;. – Prashant Agarwal Feb 26 '18 at 12:28
  • If you run this code... `var object = {}; object["property"] = "value"; console.log(object);` ...the output will result in an invalid JSON since a string is expected for the attribute name "property". Maybe I misunderstood, but what generates a valid JSON would be the command... `var object = {}; object["\"property\""] = "value"; console.log(object);` ...so I think it would be important to clarify this. Thanks! =D – Eduardo Lucio Nov 11 '19 at 21:16
  • 1
    @EduardoLucio That's because you should be using `JSON.stringify`. – Solomon Ucko May 29 '20 at 00:16
  • @SolomonUcko The command `var object = {}; object["property"] = "value"; console.log(object);` will generate this INVALID JSON on my chrome console: `{property: "value"}`. But, the command `var object = {}; object["\"property\""] = "value"; console.log(object);` will generate this VALID JSON on my chrome console: `{"property": "value"}`. You can test on this website https://jsonlint.com/ . =D – Eduardo Lucio May 29 '20 at 02:45
  • 1
    @EduardoLucio The issue is that `console.log` is not intended for serialization. Use `console.log(JSON. stringify(object))`. – Solomon Ucko May 29 '20 at 02:48
220
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);
Cody
  • 9,785
  • 4
  • 61
  • 46
  • 8
    Just what I was looking for, adding an element when the name must be constructed programmatically – quilkin Feb 02 '15 at 20:33
  • when jsonObj in itself would contain more than one element, then: ---> jsonObj["members"].anyname = "value"; <--- adds an element at the first level. This is particulary interesting in a situation like: ---> for (var key in jsonObj ) { jsonObj[key].newAttrib= 'something '; } – Martin Jul 29 '23 at 13:14
170

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';
bluish
  • 26,356
  • 27
  • 122
  • 180
FlySwat
  • 172,459
  • 74
  • 246
  • 311
129

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

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

It's allow you to add sub objects:

people = { ...people, city: { state: 'California' }};

the result would be:

{  
   "id": 4,
   "firstName": "John",
   "secondName": "Forget",
   "city": {  
      "state": "California"
   }
}

You also can merge objects:

var mergedObj = { ...obj1, ...obj2 };
Cassio Seffrin
  • 7,293
  • 1
  • 54
  • 54
81

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.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
leo
  • 811
  • 6
  • 2
  • @Sunil Garg How would you store that value as a child to some parent in the original object? –  Apr 09 '18 at 00:10
17

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.

Victor Augusto
  • 2,406
  • 24
  • 20
7
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

Ivan
  • 111
  • 1
  • 4
6

You can also dynamically add attributes with variables directly in an object literal.

const amountAttribute = 'amount';
const foo = {
                [amountAttribute]: 1
            };
foo[amountAttribute + "__more"] = 2;

Results in:

{
    amount: 1, 
    amount__more: 2
}
Stefan Rein
  • 8,084
  • 3
  • 37
  • 37
2

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}}
Georgios Syngouroglou
  • 18,813
  • 9
  • 90
  • 92
0

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.

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189
0

Following worked for me for add a new field named 'id'. Angular Slickgrid usually needs such id

  addId() {
     this.apiData.forEach((item, index) => {
     item.id = index+1;
  });
Anish Kutti
  • 337
  • 2
  • 7