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 get data from localstorage in javascript
- How to make entire Div clickable in javascript
- Generate 6 digit random number in javascript
- Deault order of record in datatable
- How to Set data to localstorage in javascript
- Short-circuits conditionals
- Get multiplication in javascript using array input
- Apexcharts example code
- On click enter redirect to another URL with parameters in javascript
- How to display for slash as a string in javascript HTML
- Execute function with condition in javascript
- Javascript get only 10 characters from string
- ReferenceError: $ is not defined
- How to check caps lock is on in javascript
- Javascript get data-id attribute value
- ReferenceError: Cannot access 'myFunction' before initialization
- How to preview a word document in HTML using javascript
- Get hostname from URL in javascript
- Hide div on click outside of element in javascript/jQuery
- Apex chart bar chart
- Custom slider js
- Javascript set timeout function with example code
- How to get the length of a number in JavaScript
- How to get query string value in javascript
- How to show and hide placeholder text