How to get the first property of a JSON object with JavaScript?

Sometimes, we want to get the first property of a JSON object with JavaScript.

In this article, we’ll look at how to get the first property of a JSON object with JavaScript.

How to get the first property of a JSON object with JavaScript?

To get the first property of a JSON object with JavaScript, we can use the Object.keys method.

For instance, we write:

const json = `{
  "category1": ["image/url/1.jpg", "image/url/2.jpg"],
  "category2": ["image/url/3.jpg", "image/url/4.jpg"]
}`
const obj = JSON.parse(json)
const [key] = Object.keys(obj)
console.log(key)

to define the json JSON string.

Then we parse it into an object with JSON.parse.

Then we call Object.keys with obj to return an array of the object keys.

And we get the first one with destructuring.

As a result, we see that key is 'category1'.

Conclusion

To get the first property of a JSON object with JavaScript, we can use the Object.keys method.