Categories
JavaScript Answers

How to fill a JavaScript object literal with many static key/value pairs efficiently?

Spread the love

Sometimes, we want to fill a JavaScript object literal with many static key/value pairs efficiently.

In this article, we’ll look at how to fill a JavaScript object literal with many static key/value pairs efficiently.

How to fill a JavaScript object literal with many static key/value pairs efficiently?

To fill a JavaScript object literal with many static key/value pairs efficiently, we create a map.

For instance, we write

const map = new Map([
  ["key1", "value1"],
  ["key2", "value2"],
]);
const value = map.get("key1");

to call the Map constructor with an array of key-value pair arrays to create a map.

Then we get the value by the get with 'key1'.

Conclusion

To fill a JavaScript object literal with many static key/value pairs efficiently, we create a map.

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 *