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

How to add rounded borders to div elements

As shown below: CSS CodeCopy content to clipboard...

Detailed explanation of the execution process of JavaScript engine V8

Table of contents 1. V8 Source 2. V8 Service Targ...

NULL and Empty String in Mysql

I recently came into contact with MySQL. Yesterda...

CSS to achieve fast and cool shaking animation effect

1. Introduction to Animate.css Animate.css is a r...

Centos7 install mysql5.6.29 shell script

This article shares the shell script of mysql5.6....

Detailed example of MySQL joint table update data

1.MySQL UPDATE JOIN syntax In MySQL, you can use ...

The easiest way to make a program run automatically at startup in Linux

I collected a lot of them, but all ended in failu...

Mysql: The user specified as a definer ('xxx@'%') does not exist solution

During the project optimization today, MySQL had ...

Detailed analysis of classic JavaScript recursion case questions

Table of contents What is recursion and how does ...

Provides helpful suggestions for improving website design

<br />Scientifically Design Your Website: 23...

JavaScript to achieve digital clock effects

This article example shares the specific code for...

Introduction to CSS BEM Naming Standard (Recommended)

1 What is BEM Naming Standard Bem is the abbrevia...

How to use js to communicate between two html windows

Scenario: When page A opens page B, after operati...

Detailed Example of CSS3 box-shadow Property

CSS3 -- Adding shadows (using box shadows) CSS3 -...