How to Add an Element to a JSON Object using JavaScript?
Last Updated : 11 Jul, 2025
In JavaScript to add an element to a JSON object by simply assigning a value to a new key. We can use the approaches mentioned below.
Let's first create a JSON object in JavaScript and then implement the possible approaches.
let jsonObject = { key1: 'value1', key2: 'value2' };
Using Dot Notation to add an element to a JSON object
Uses the dot notation (object.property
) to directly assign a new property to the JSON object.
Example: This code initializes a JSON object `jsonObject` with two key-value pairs. It then adds a new key `newKey` with the value `'newValue'` using dot notation. Finally, it logs the updated `jsonObject` to the console.
JavaScript let jsonObject = { key1: 'value1', key2: 'value2' }; jsonObject.newKey = 'newValue'; console.log(jsonObject);
Output{ key1: 'value1', key2: 'value2', newKey: 'newValue' }
Using Bracket notation to add an element to a JSON object
Uses the bracket notation (object['property']
) to add a new property to the JSON object.
Example: This code initializes a JSON object `jsonObject` with two key-value pairs. It then adds a new key `newKey` with the value `'newValue'` using bracket notation. Finally, it logs the updated `jsonObject` to the console.
JavaScript let jsonObject = { key1: 'value1', key2: 'value2' }; jsonObject['newKey'] = 'newValue'; console.log(jsonObject);
Output{ key1: 'value1', key2: 'value2', newKey: 'newValue' }
Using Object.assign()
Utilizes the Object.assign()
method to merge the original object with a new object containing the additional key-value pair.
Example: This code initializes a JSON object `jsonObject` with two key-value pairs. It then creates a new object by merging `jsonObject` with an object containing the additional property `{ newKey: 'newValue' }` using `Object.assign()`. Finally, it logs the updated `jsonObject` to the console.
JavaScript let jsonObject = { key1: 'value1', key2: 'value2' }; jsonObject = Object.assign({}, jsonObject, { newKey: 'newValue' }); console.log(jsonObject);
Output{ key1: 'value1', key2: 'value2', newKey: 'newValue' }
Using Spread operator to add an element to a JSON object
Uses the spread operator (...
) to create a new object by spreading the properties of the original object and adding the new property.
Example: This code initializes a JSON object `jsonObject` with two key-value pairs. It then creates a new object by spreading the properties of `jsonObject` and adding the property `newKey` with the value `'newValue'`. Finally, it logs the updated `jsonObject` to the console.
JavaScript let jsonObject = { key1: 'value1', key2: 'value2' }; jsonObject = { ...jsonObject, newKey: 'newValue' }; console.log(jsonObject);
Output{ key1: 'value1', key2: 'value2', newKey: 'newValue' }
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics
My Profile