In JavaScript, elements can be added to a JSON object by assigning a value to a new key.
- JSON objects are mutable in JavaScript.
- New properties can be added dynamically.
- No special method is required.
let jsonObject = {
key1: 'value1',
key2: 'value2'
};
Using Dot Notation to add an element to a JSON object
Dot notation allows adding a new property to a JSON object by directly assigning a value to it.
- Uses object.property = value syntax.
- Simple and readable approach.
- Works when the key name is valid identifier.
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
Bracket notation allows adding properties to a JSON object using dynamic or non-standard keys.
- Uses object['property'] = value syntax.
- Supports keys with spaces or special characters.
- Useful when key names are stored in variables.
let jsonObject = {
key1: 'value1',
key2: 'value2'
};
jsonObject['newKey'] = 'newValue';
console.log(jsonObject);
Output
{ key1: 'value1', key2: 'value2', newKey: 'newValue' }
Using Object.assign()
Object.assign() method adds new elements by merging an existing object with another object containing additional properties.
- Copies properties from source objects to a target object.
- Allows adding multiple key-value pairs at once.
- Modifies the target object directly.
- Useful for merging or extending objects.
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
The spread operator creates a new JSON object by copying existing properties and adding new ones.
- Uses { ...object, newKey: value } syntax.
- Does not modify the original object.
let jsonObject = {
key1: 'value1',
key2: 'value2'
};
jsonObject = { ...jsonObject, newKey: 'newValue' };
console.log(jsonObject);
Output
{ key1: 'value1', key2: 'value2', newKey: 'newValue' }