In this article, we will learn how to add an element to the JSON object using JavaScript. In order to add Key/value pair to a JSON object, Either we use dot notation or square bracket notation. Both methods are widely accepted.
Example 1: This example adds {“prop_4”: “val_4”} to the GFG object by using dot notation.
Javascript
let GFG = { prop_1: "val_1" , prop_2: "val_2" , prop_3: "val_3" }; GFG.prop_4 = "val_4" ; console.log(JSON.stringify(GFG)); |
{"prop_1":"val_1","prop_2":"val_2","prop_3":"val_3","prop_4":"val_4"}
Example 2: This example adds {“prop_4”: “val_4”} to the GFG object by using square bracket notation.
Javascript
let GFG = { prop_1: "val_1" , prop_2: "val_2" , prop_3: "val_3" }; GFG[ "prop_4" ] = "val_4" ; console.log(JSON.stringify(GFG)); |
{"prop_1":"val_1","prop_2":"val_2","prop_3":"val_3","prop_4":"val_4"}