Using bracket notation or the defineProperty() method you can add key/value pair in JavaScript object dynamically.
JavaScript Object defineProperty() method adds or modifies an existing property on an object and returns the object. The defineProperty() method, being a static method, is called using the Object class name.
Add key/value pair in JavaScript object dynamically
Simple example code adds a new key to the existing object.
<!DOCTYPE html>
<html>
<body>
<script>
const obj = {
'msg': 'Hello',
}
const key = "Code"
obj[key] = "Up"
console.log(obj)
</script>
</body>
</html>
Output:
Using Object.defineProperty() method
<script>
const getId = () => {
//API call and other stuff
return "ID"
}
const objA = {
codez: 'up',
test: '123',
}
console.log(objA)
const key3 = getId()
Object.defineProperty(objA, key3,
{
value: 'Nothing',
writable: true,
enumerable: true,
configurable: true
})
console.log(objA)
</script>
Output:
Object { codez: "up", test: "123" }
Object { codez: "up", test: "123", ID: "Nothing" }
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