How can I add a key/value pair to a JavaScript object
How can I add a key/value pair to a JavaScript object
In this article, we will see how to solve "How can I add a key/value pair to a JavaScript object".
You can add key/value pair to a javascript object using dot notation and square brackets notation.-
Add key/value pair to javascript object using dot notation
<script> const obj = { key1: 'value1', key2: 'value2' }; obj.key3 = "value3"; console.log(obj); </script>
Output:
{ key1: 'value1', key2: 'value2', key3: 'value3' }
You have to use dot notation in between object and new key (object.key) and assign value to key using assignment operator (=) in javascript to add a new key and value pair to an existing javascript object.
-
Add key/value pair to javascript object usign square bracket notation
<script> const obj = { key1: 'value1', key2: 'value2' }; obj["key3"] = "value3"; console.log(obj); </script>
Output:
{ key1: 'value1', key2: 'value2', key3: 'value3' }
You can add a new key/value pair to object in javascript using square ([]) notation. It will helps you to add a new values (key/value) to an existing object in javascript.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: Javascript
- How to check caps lock is on in javascript
- Check if value exists in array javascript
- Short-circuits conditionals
- Remove hostname from URL in javascript
- How to open modal after redirect
- Uncaught TypeError: Illegal invocation
- How to switch between Dark Mode and Light Mode based on cookie in Javascript
- Copy one array to another in javascript
- Uncaught TypeError: Cannot read property 'addEventListener' of undefined
- ReferenceError: $ is not defined
- Apexcharts example code
- How to add a property to object with condition in javascript
- How to push string in an array in Javascript
- How to fixed bootstrap navbar at top on scroll
- JavaScript test() Method
- Uncaught SyntaxError: Identifier 'CODE' has already been declared
- Custom slider js
- How to remove duplicate values from array in javascript
- Javascript set timeout function with example code
- Concat variable with string in javascript
- Javascript get data-id attribute value
- Javascript get only 10 characters from string
- How to add key/value pair to existing form data
- How to make entire Div clickable in javascript
- Trim the leading and trailing comma from string in Javascript