Object.entries usage you don't know in JavaScript

Object.entries usage you don't know in JavaScript

Preface

Usually we often use static methods on the Object class, such as Object.keys, Object.values, Object.assign, etc., but we may rarely use the Object.entries method. This article will explain two tips for the Object.entries method.

effect

The Object.entries() method returns an array of key-value pairs of the enumerable properties of a given object, in the same order as they would be returned by a for…in loop (the difference is that a for-in loop also enumerates properties in the prototype chain).

Example

const obj = { foo: 'bar', baz: 42 };
console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]

// array like object
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]

// array like object with random key ordering
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]

// getFoo is a property which isn't enumerable
const myObj = Object.create({}, { getFoo: { value() { return this.foo; } } });
myObj.foo = 'bar';
console.log(Object.entries(myObj)); // [ ['foo', 'bar'] ]

// non-object argument will be coerced to an object
console.log(Object.entries('foo')); // [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]

// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}

// Or, using array extras
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"

1. Use for...of to iterate over common objects

Many beginners of front-end may have written the following code:

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

for (let value of obj) {
  // ...
}

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

Uncaught TypeError: obj is not iterable

Therefore, traversing ordinary objects becomes a uniform for...in traversal. However, because for...in not only traverses the object's own properties, but also traverses the object's prototype, we also need to add a filter when using it, for example:

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

You can see that this is not very elegant. The reason why ordinary objects cannot be traversed using for...of is that ordinary objects do not implement the iterator interface (I will write a special article about JS iterators). JS arrays implement the iterator interface, so the key-value array obtained through Object.entries can be traversed using for...of:

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

Object.entries returns an array of key-value pairs of the object's own enumerable properties, excluding properties on the prototype.

2. Conversion between ordinary objects and Map objects

I saw that the project converted ordinary objects into Map objects and still used for...in traversal:

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

let map = new Map();

for (let key in obj) {
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
    map.set(key, obj[key]);
  }
}

In fact, the Map constructor can accept an array of key-value pairs for initialization, which means that you can use Object.entries to convert ordinary objects into Map objects:

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

So how do you convert a Map object back into a normal object? Still using traversal? No, you can use the Object.fromEntries static method to convert:

let obj = Object.fromEntries(map);

At this point, many friends may still not understand the conversion relationship between ordinary objects, key-value pair arrays, and Map objects. I will summarize it with a picture:

Object.entries and Object.fromEntries are two opposite operations

Summarize

This is the end of this article about the Object.entries usage in JavaScript that you don’t know. For more relevant js Object.entries usage content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

refer to

  • Object.entries() - MDN documentation
  • Map() Constructor - MDN documentation
You may also be interested in:
  • js array fill() filling method
  • Detailed usage of js array forEach instance
  • Detailed discussion of several methods for deduplicating JavaScript arrays
  • Summary of JS tips for creating or filling arrays of arbitrary length
  • Detailed explanation of the deep and shallow cloning principles of JavaScript arrays and non-array objects
  • Detailed explanation of JavaScript array deduplication
  • js array entries() Get iteration method

<<:  The solution of html2canvas that pictures cannot be captured normally

>>:  Solve the problem of starting two ports that occupy different ports when docker run

Recommend

In-depth explanation of the locking mechanism in MySQL InnoDB

Written in front A database is essentially a shar...

WeChat applet implements calculator function

WeChat Mini Programs are becoming more and more p...

Detailed explanation of persistent storage of redis under docker

In this chapter, we will start to operate redis i...

CSS beginner tutorial: background image fills the entire screen

If you want the entire interface to have a backgr...

How to write elegant JS code

Table of contents variable Use meaningful and pro...

HTML+CSS+JavaScript to achieve list loop scrolling example code

Description: Set a timer to replace the content of...

Element-ui's built-in two remote search (fuzzy query) usage explanation

Problem Description There is a type of query call...

Solve the problem of docker container exiting immediately after starting

Recently I was looking at how Docker allows conta...

MySQL partition table is classified by month

Table of contents Create a table View the databas...

Pitfalls and solutions encountered in MySQL timestamp comparison query

Table of contents Pitfalls encountered in timesta...

What is BFC? How to clear floats using CSS pseudo elements

BFC Concept: The block formatting context is an i...