Use the dot notation to Add property to an object in JavaScript. The below code added the foo
property to the obj
object above with value 1.
obj.foo = 1;
You can also add a property by using the bracket notation:
obj['foo'] = 1;
Both ways do the same but bracket nation can have invalid property identifiers in the string.
Add property to object JavaScript
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
var obj = { Name: "Joe" };
obj.Age = 25;
obj['Country'] = "USA"
console.log(obj)
</script>
</body>
</html>
Output:
Is it possible to add dynamically named properties to JavaScript objects?
Answer: Yes, it is possible, see below code.
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);
Do comment if you have any doubts or suggestions on this JS object topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version