How do I add a key/value pair to a JavaScript object?
The problem
Suppose I have the following object literal:
var obj = {key1: value1, key2: value2};
How can I add {key3: value3}
to object obj
?
Answer
There are two ways to add a new property to an object:
Use dot notation
If you know the key name of the property, the key3
in this example
obj.key3 = "value3";
Use square bracket notation
This form allow to give the key name dynamically.
obj["key3"] = "value3";
This form is widely used when the key name is dynamically determined. Like in this example:
var getProperty = function (propertyName) {
return obj[propertyName];
};
getProperty("key1");
getProperty("key2");
getProperty("key3");
References & Resources
- N/A
Latest Post
- Dependency injection
- Directives and Pipes
- Data binding
- HTTP Get vs. Post
- Node.js is everywhere
- MongoDB root user
- Combine JavaScript and CSS
- Inline Small JavaScript and CSS
- Minify JavaScript and CSS
- Defer Parsing of JavaScript
- Prefer Async Script Loading
- Components, Bootstrap and DOM
- What is HEAD in git?
- Show the changes in Git.
- What is AngularJS 2?
- Confidence Interval for a Population Mean
- Accuracy vs. Precision
- Sampling Distribution
- Working with the Normal Distribution
- Standardized score - Z score
- Percentile
- Evaluating the Normal Distribution
- What is Nodejs? Advantages and disadvantage?
- How do I debug Nodejs applications?
- Sync directory search using fs.readdirSync