![]() |
VOOZH | about |
A JavaScript object has a key-value pair, and it can be of variable length. We first need to declare an object and assign the values to that object for that there can be many methods.
Below are the methods to add a key/value pair to a JavaScript object:
Table of Content
In this approach, we will directly access the key of an object by "." for assigning the value to it. It can be a repeated method as every time we need to define a different key for different values.
Example: This example shows the implementation of the above approach.
Output:
In this approach, we are using Bracket to access the key and assign the value to it.
Example: This example shows the implementation of the above approach.
Output:
In this approach, we are using Object.assign() method to assign the key and value to the object. We are passing the object name and the field that we want to use in the object. It assign those fields to the given object.
Example: This example shows the implementation of the above approach.
Output:
If your key name is inside a variable, you must use bracket notation.
Output:
In this approach, we are using Object.defineProperty() method to assign the key and value to the object. We are passing the object name and the field that we want to use in the object with some extra specification that is served by the method itself.
Example: This example shows the implementation of the above approach.
Output:
In this approach, we are using Object.entries() to convert the object into an array of key-value pairs, then adding the new key-value pair, and converting it back to an object using Object.fromEntries().
Example: This example shows the implementation of the above approach.
The spread operator is used to copy all properties from one object into another, or merge objects easily.
Output:
A Map allows keys of any type and maintains insertion order. It is used when you need more flexibility.
Output: