How to get the key and value of an object in JavaScript?

Sometimes, we want to get the key and value of an object in JavaScript.

In this article, we’ll look at how to get the key and value of an object in JavaScript.

How to get the key and value of an object in JavaScript?

To get the key and value of an object in JavaScript, we can use the Object.entries method.

For instance, we write:

const topBrands = [{
  'Adidas': 100
}, {
  'Nike': 50
}];

for (const t of topBrands) {
  for (const [key, val] of Object.entries(t)) {
    console.log(key, val)
  }
}

to loop through the entries of the topBrands array with the for-of loop.

In the loop, we get the key-value entries as an array with Object.entries.

Then we loop through the key-value arrays returned with another for-of loop and log the key and val values.

Therefore, we see:

"Adidas", 100
"Nike", 50

logged.

Conclusion

To get the key and value of an object in JavaScript, we can use the Object.entries method.