JSON Add a Key to an object

JSON Adding Keys to the object

In the following example, we will add new keys (married and partner) to the first object in an array (data) by using JSON's dot notation and bracket notation.

Example

HTML Editor
<!DOCTYPE html> <html lang="en-US"> <body> <h1>JSON Adding Keys to the object</h1> <button onclick="myFunction()">Click Me</button> <script> var data = [ { "name": "Mike", "age": 36 } ] function myFunction(){ // Adding a key (married) to the first object by using dot notation data[0].married = true; // Adding a key (partner) to the first object by using bracket notation data[0]["partner"] = "Jade"; console.log(data); } </script> </body> </html>

Syntax

obj.newKey = "value"; //or obj["newKey"] = "value";

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author