Add new attribute (element) to JSON object using JavaScript

Viewed 1251909

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

11 Answers

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.

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

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

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
}

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