Categories
JavaScript Answers

How to Access the First Property of a JavaScript Object?

Spread the love

In our JavaScript programs, sometimes we only want to access the first property of a JavaScript object.

In this article,e we’ll look at various ways we can access only the first property of a JavaScript object.

Object.keys

The Object.keys method returns an array with the string keys of an object.

So we can access the first property in an object by writing:

const obj = {
  a: 1,
  b: 2
};
const [prop] = Object.keys(obj)
console.log(obj[prop])

We have the obj object with some properties.

And we call Object.keys and destructure the first key from the returned array and assign it to prop .

And then we get the value of the first property returned with obj[prop] .

So we get 1 from the console log.

for-in Loop and break

We can use the for-in loop to loop through an object and break after the first iteration.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

for (const prop in obj) {
  console.log(obj[prop])
  break;
}

We have the for-in loop and log the first property value returned.

prop has the property key string.

Then we use break to stop iterating.

Object.values

We can use the Object.values method to get the values from an object.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

const [value] = Object.values(obj)
console.log(value)

If we just want the first property value, then we can just use Object.values and destructure it from the returned array.

Object.entries

We can use the Object.entries method to return an array of arrays of key-value pairs.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

const [
  [key, value]
] = Object.entries(obj)
console.log(key, value)

to get the first key-value pair from the returned array.

We just destructure it from the nested array.

And so key is 'a' and value is 1.

Conclusion

We can use JavaScript object static methods or the for-in loop to get the first property from a JavaScript object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *