Categories
JavaScript Answers

What are the Best Ways to Get the Key of a JavaScript Object?

Spread the love

Oftentimes, we have to get the keys and values of a JavaScript object.

In this article, we’ll look at how to get the keys and values from an object.

Get Object Keys with the Object.keys Method

We can use the Object.keys method to get the keys of an object.

It returns an array with the object’s string keys.

For instance, we can write:

const obj = {
  first: 'someVal',
  second: 'otherVal'
};
const keys = Object.keys(obj)
console.log(keys)

Then keys is [“first”, “second”] .

Get Object Property Values with the Object.values Method

To get an object’s property values, we can use the Object.values method.

It returns an array with the object’s property values.

For example, we can write:

const obj = {
  first: 'someVal',
  second: 'otherVal'
};
const values = Object.values(obj)
console.log(values)

Then values is [“someVal”, “otherVal”] .

Get Object Key-Value Pairs with the Object.entries Method

To get an array of key-value pair arrays of an object, we can use the Object.entries method.

For instance, we can write:

const obj = {
  first: 'someVal',
  second: 'otherVal'
};
const pairs = Object.entries(obj)
console.log(pairs)

Then pairs is:

[
  [
    "first",
    "someVal"
  ],
  [
    "second",
    "otherVal"
  ]
]

Conclusion

We can get a JavaScript’s object keys and values separately or together easily with some JavaScript object methods.

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 *