Table of Contents
Object.fromEntries
Use Object.fromEntries to convert the array into Object
Use Object.fromEntries to convert Map into an object
Type error of object: trying to use Object.fromEntries to convert other types to objects
Object.fromEntries vs Object.entries
Object to object conversion
Alternatives to array to object
Use the reduce method to convert an array into an object
Use the library to convert arrays into objects
_.object
_.fromPairs
Browser support
Home Web Front-end JS Tutorial An in-depth analysis of Object.fromEntries() in ES10

An in-depth analysis of Object.fromEntries() in ES10

Apr 16, 2021 pm 07:03 PM
javascript

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.

An in-depth analysis of Object.fromEntries() in ES10

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: '?' }
Copy after login

Object.fromEntries


We know that the object structure is a combination of keys and values, as shown below:

const object = {
  key: 'value',
};
Copy after login

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']
]
Copy after login

Use Object.fromEntries to convert the array into an object:

Object.fromEntries(nestedArray);
// { key 1: "value 1", key 2: "value 2"}
Copy after login

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"}
Copy after login

Let’s use Object.fromentries to convert the map to an object

Object.fromEntries(map);
// { key 1: "value 1", key 2: "value 2"}
Copy after login

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.

An in-depth analysis of Object.fromEntries() in ES10

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' }
Copy after login

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", "?"] ]
Copy after login

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: '?' }
Copy after login

Alternatives to array to object


Object.fromEntriesis 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' }
Copy after login

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' }
Copy after login
_.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' }
Copy after login

Browser support


An in-depth analysis of Object.fromEntries() in ES10

##Original address: https://medium.com/@samanthaming/javascript-object-fromentries-4395660334d1

Author: Shadeed

For more programming-related knowledge, please visit:

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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 and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

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

See all articles