Add new Key - Value pair to an object in JavaScript
Question:
How to add new Key - Value pair to an object in JavaScript? Answer:
user.newKey = newValue;
// OR
user['newKey'] = newValue;
// OR
newUser = {...user, newKey: 'newValue'};
// OR
Object.assign(user, {newKey: 'newValue'});
Description:
In JavaScript, you can add new key-value pairs (new properties) to an object using multiple syntaxes. The dot notation is the easiest: object.newKey = newValue;
The bracket notation is very similar but allows key names with a dash, a hyphen, or space: object['new-key'] = newValue;
You can also use the Object.assign()
method, that copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object. Object.assign(user, {newKey: 'newValue'});
And finally, you can use spread object literal: newUser = {...user, newKey: 'newValue'};
Reference:
JavaScript Object reference
Share "How to add new Key - Value pair to an object in JavaScript?"
Related snippets:
Tags:
add, property, key, value, key/value pair, object, javascript Technical term:
Add new Key - Value pair to an object in JavaScript