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!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft