An in-depth analysis of Object.fromEntries() in ES10
This article will take you to learn more about Object.fromEntries() in ES10. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
We know that Object.entries()
converts the object into an array of key-value pairs of its own enumerable properties. Similarly, we can also convert the key-value pair array into an object.
const keyValuePair = [ ['cow', '?'], ['pig', '?'], ] Object.fromEntries(keyValuePair); // { cow: '?', pig: '?' }
Object.fromEntries
We know that the object structure is a combination of keys and values, as shown below:
const object = { key: 'value', };
Based on this logic, if we want to convert something into an object, we must pass the key and value.
There are two types of parameters that satisfy these requirements:
Arrays with nested key-value pairs
Map Object
[Recommended learning: javascript advanced tutorial]
Use Object.fromEntries
to convert the array into Object
The following is a nested array of key-value pairs
const nestedArray = [ ['key 1', 'value 1'], ['key 2', 'value 2'] ]
Use Object.fromEntries
to convert the array into an object:
Object.fromEntries(nestedArray); // { key 1: "value 1", key 2: "value 2"}
Use Object.fromEntries
to convert Map into an object
ES6 brings us a file called map 's new object, which is very similar to the object.
TC39: A map object is a collection of key/value pairs, where both key and value can be arbitrary ECMAScript language values.
Let’s create a Map object:
// 使用构造函数 const map = new Map([ ['key 1', 'value 1'], ['key 2', 'value 2'] ]) // 或者我们可以使用实例方法“set” const map = new Map() map.set('key 1', 'value 1') map.set('key 2', 'value 2') // 结果 Map(2) {"key 1" => "value 1", "key 2" => "value 2"}
Let’s use Object.fromentries
to convert the map to an object
Object.fromEntries(map); // { key 1: "value 1", key 2: "value 2"}
Type error of object: trying to use Object.fromEntries
to convert other types to objects
Pass the following types in Object.fromEntries
will cause an error caught TypeError
.
Make sure the passed value has a key-value pair.
Object.fromEntries vs Object.entries
Object.fromEntries
is the reverse of Object.entries
. The Object.entries()
method returns an array of key-value pairs for the given object's own enumerable properties, while the Object.fromEntries()
method converts the list of key-value pairs into an object .
const object = { key1: 'value1', key2: 'value2' } const array = Object.entries(object) // [ ["key1", "value1"], ["key2", "value2"] ] Object.fromEntries(array) // { key1: 'value1', key2: 'value2' }
Object to object conversion
If you read the TC39 proposal, this is where this new method was introduced reason. Before the introduction of Object.entries
, it was more troublesome to convert some non-object structures into objects.
Usually, when we choose to use Object.entries
, it is because it gives us access to many nifty array methods, such as filter
. But after doing the conversion, we're a bit stuck with that array.
const food = { meat: '?', broccoli: '?', carrot: '?' } // ? 卡在这结果上... const vegetarian = Object.entries(food).filter( ([key, value]) => key !== 'meat', ) // [ ["broccoli", "?"], ["carrot", "?"] ]
Okay! We can take advantage of all these useful array methods and still return objects. Finally, object to object conversion?
const food = { meat: '?', broccoli: '?', carrot: '?' } const vegetarian = Object.fromEntries( Object.entries(food).filter(([key, value]) => key !== 'meat'), ) // { broccoli: '?', carrot: '?' }
Alternatives to array to object
Object.fromEntries
is ES10 push It's very new, and maybe the browser support is friendly enough. So let's see how to convert an array with a key-value structure into an object.
Use the reduce method to convert an array into an object
A popular way to convert an array into an object is to use reduce
.
const array = [ ['key1', 'value1'], ['key2', 'value2'] ] const map = new Map([ ['key1', 'value1'], ['key2', 'value2'] ]) function toObject(pairs) { return Array.from(pairs).reduce( (acc, [key, value]) => Object.assign(acc, { [key]: value}), {} ) } // 结果 // { key1: 'value1', key2: 'value2' }
Use the library to convert arrays into objects
Lodash also provides methods for converting key-value pairs into objects.
_.object
Convert an array to an object. Pass a single list of [key, value]
pairs, or a list of keys and a list of values.
const array = [ ['key1', 'value1'], ['key2', 'value2'] ] _.object(array) // { key1: 'value1', key2: 'value2' }
_.fromPairs
_.fromPairs
is the reverse of _.toPairs
, its method returns a An object composed of key-value pairs.
const array = [ ['key1', 'value1'], ['key2', 'value2'], ] _.fromPairs(array) // { key1: 'value1', key2: 'value2' }
Browser support
For more programming-related knowledge, please visit:##Original address: https://medium.com/@samanthaming/javascript-object-fromentries-4395660334d1
Author: Shadeed
Introduction to Programming! !
The above is the detailed content of An in-depth analysis of Object.fromEntries() in ES10. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
