There are many methods to access the first value of an object in JavaScript some of them are discussed below:
Example 1: This example accesses the first value object of GFG_object by using object.keys() method.
html
< h1 style = "color:green;" > neveropen </ h1 > < p id = "GFG_UP" style = "color:green;" > </ p > < button onclick = "gfg_Fun()" > find First </ button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px;" > </ p > < script > // Declare an object var GFG_object = {prop_1: "GFG_1", prop_2: "GFG_2", prop_3: "GFG_3"}; var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); // Use SON.stringify() function to take object // or array and create JSON string el_up.innerHTML = JSON.stringify(GFG_object); // Access the first value of an object function gfg_Fun() { el_down.innerHTML = GFG_object[Object.keys(GFG_object)[0]]; } </ script > |
Output:
Example 2: This example accesses the first value of object GFG_object by looping through the object and breaking the loop on accessing the first value.
html
< h1 style = "color:green;" > neveropen </ h1 > < p id = "GFG_UP" style = "color:green;" ></ p > < button onclick = "gfg_Fun()" > find First </ button > < p id = "GFG_DOWN" style = "color:green;font-size:20px;" ></ p > < script > // Declare an object var GFG_object = {prop_1: "GFG_1", prop_2: "GFG_2", prop_3: "GFG_3"}; var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); // Use SON.stringify() function to take object // or array and create JSON string el_up.innerHTML = JSON.stringify(GFG_object); // Function to access the first value of an object function gfg_Fun() { for (var prop in GFG_object) { el_down.innerHTML = GFG_object[prop] break; } } </ script > |
Output:
Example 3: This example accesses the first value of objectGFG_object by using object.values() method.
html
< h1 style = "color:green;" > neveropen </ h1 > < p id = "GFG_UP" style = "color:green;" ></ p > < button onclick = "gfg_Fun()" > find First </ button > < p id = "GFG_DOWN" style = "color:green; font-size: 20px;" ></ p > < script > // Declare an object var GFG_object = {prop_1: "GFG_value", prop_2: "GFG_2", prop_3: "GFG_3"}; var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); // Use SON.stringify() function to take object // or array and create JSON string el_up.innerHTML = JSON.stringify(GFG_object); // Function to access the first value of an object function gfg_Fun() { el_down.innerHTML = Object.values(GFG_object)[0]; } </ script > |
Output: