I’m Garfield at 🐱. If you like my article, please feel free to like it and share it

We often use static methods on the Object class, such as Object.keys, Object.values, object. assign, etc., but we probably don’t use object. entries very often. This article explains two tricks of the Object.entries method.

1. Use the for… Of traverses ordinary objects

If you’re new to the front end, you’ve probably written the following code:

let obj = {
  a: 1.b: 2
}

for (let value of obj) {
  // ...
}
Copy the code

But when I run it, I find that, oh ho, there is an error:

Uncaught TypeError: obj is not iterable

As a result, traversing ordinary objects turns into a uniform for… The in traverse. But because of the for… In not only traverses the object’s own properties, but also traverses the object’s prototype, so we need to add a filter when we use it, for example:

for (let key in obj) {
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
    // ...}}Copy the code

And you can see it’s not very elegant. The reason for not using “for” for ordinary objects is that… Of traversal, because ordinary objects do not implement the Iterator interface (there will be a whole article on JS iterators). JS arrays implement the Iterator interface, so array-based key-value pairs derived from Object.entries can use for… Of traversal:

for (let [key, value] of Object.entries(obj)) {
  // ...
}
Copy the code

Object.entries will return an array of key-value pairs for the Object’s own enumerable properties, excluding the properties on the prototype

2. Common objects are converted to Map objects

See the project turning normal objects into Map objects and using for… In traversing the:

let obj = {
  a: 1.b: 2
}

let map = new Map(a);for (let key in obj) {
  if (Object.prototype.hasOwnProperty.call(obj, key)) { map.set(key, obj[key]); }}Copy the code

In fact, the Map constructor accepts a key-value pair array initialization, which means that you can use Object.entries to turn normal objects into Map objects:

let map = new Map(Object.entries(obj));
Copy the code

So how do Map objects go back to normal objects? Do you still use traversal? No, you can use the object. fromEntries static method to convert:

let obj = Object.fromEntries(map);
Copy the code

Key/value array (Map); key/value array (key/value);

Object.entries and object. fromEntries are opposite operations

reference

Object.entries() – MDN document

Map() constructor – MDN document