How to access the first value of an object using JavaScript?


In this article, you will understand how to access the first value of an object using JavaScript.

The first value of the object is the first property located at position[0] of the object. The object can be a key-value object or an array object.

Example 1

In this example, let's consider a key-value pair object.

const inputObject = {1: 'JavaScript', 2: 'Python', 3: 'HTML'};
console.log("A key-value pair object is defined and its values are: ", inputObject)

console.log("
The first value of the object is: ") const firstValue = Object.values(inputObject)[0]; console.log(firstValue);

Explanation

  • Step 1 − Define a key-value pair object ‘inputObject’.

  • Step 2 − Define a variable ‘firstValue’ and assign the value of the first position of the object i.e (inputObject)[0] to it.

  • Step 3 − Display the value of ‘firstValue’ as result.

Example 2

const arrayObject = ['JavaScript', 'Python', 'HTML'];
console.log("An array object is defined and its values are: ", arrayObject)

console.log("
The first value of the object is: ") const firstValue = Object.values(arrayObject)[0]; console.log(firstValue);

Explanation

  • Step 1 − Define an array ‘arrayObject’.

  • Step 2 − Define a variable ‘firstValue’ and assign the value of the first position of the object i.e (arrayObject)[0] to it.

  • Step 3 − Display the value of ‘firstValue’ as result.

Updated on: 16-Feb-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements