Add key/value pair to an object in JavaScript
This tutorial will show you how you can add key/value pair to an object in JavaScript. Here are some examples below to add key/value pair to an object.
Using dot notation
We can access an object property by using dot notation. Here is the JavaScript program below to add key/value pair to an object.
Here is the Javascript program below:
var myObj = { name: "sam", lastName: "Raja" }; myObj.age = 32; console.log(myObj);
In the above program, I have defined an object myObj
with two properties name
and lastName
.
Then added a new property age
to the object and set its value to 32
.
After that, I logged the entire object to the console using console.log(myObj)
.
Output:
{ name: 'sam', lastName: 'Raja', age: 32 }
Using square bracket notation
The square bracket notation is also a way that is used to access an object property. The object properties can be accessed using a string as the property. We can also use the square bracket notation to set the value of an object property.
Here is a JavaScript program to add key/value pair to an object using square bracket notation.
var myObj = { name: "sam", lastName: "Raja" }; myObj["age"] = 32; console.log(myObj);
Output:
{ name: 'sam', lastName: 'Raja', age: 32 }
Using the object.assign method
An object can be copied by the object.assign
method into a single object that contains all enumerable own properties of a given object.
Here is the JavaScript program below:
var myObj = { name: "sam", lastName: "Raja" }; Object.assign(myObj, {age: 32}); console.log(myObj);
In the above program, Object.assign()
will copy the age
property from the object {age: 32}
to the myObj
object.
Now, the myObj
object has an age
property with a value 32
.
Output:
{ name: 'sam', lastName: 'Raja', age: 32 }
Using the spread operator (…)
We can use the spread operator (...
) to add key/value pair to an object. We can create a new object by this operator that contains all the properties of the original object and add a new property with the specified value.
Here is the JavaScript program below:
var myObj = { name: "sam", lastName: "Raja" }; const newObj = { ...myObj, age : 32 }; console.log(newObj);
Output:
{ name: 'sam', lastName: 'Raja', age: 32 }
Leave a Reply