Categories
JavaScript Answers

How to use an array as object keys in JavaScript?

Spread the love

Sometimes, we want to use an array as object keys in JavaScript.

In this article, we’ll look at how to use an array as object keys in JavaScript.

How to use an array as object keys in JavaScript?

To use an array as object keys in JavaScript, we can convert the array to a string.

For instance, we write:

const key = [1, 2, 3]
const obj = {
  [JSON.stringify(key)]: 'foo'
}
console.log(obj[JSON.stringify(key)])

to create the key array.

Then we convert it to a string with JSON.stringify so we can use it as a property key.

And we set the property’s value 'foo'.

Then we can access the value with obj[JSON.stringify(key)].

Therefore, the console log should log 'foo'.

Conclusion

To use an array as object keys in JavaScript, we can convert the array to a string.

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 *