Introduction to methods of traversing object properties in JS
In the same period as ECMAScript 2016 was released in June 2016, JavaScript developers will be happy to know that another set of great proposals has been reachedPhase 4 (Complete).
Translator's Note: When translating this article, these features have been supported.
Let’s list these functions:
Babel already contains most of the features from these completed proposals.
This article mainly discusses how to improve the iteration of object properties:- Use
Object.values()
Get object properties
- Use
Object.entries()
Get attributes
key/value
for...of loop, you get a simple and beautiful way of traversing the properties of an object.
Object.keys() only accesses the object itself and enumerable properties. This is reasonable since most of the time only these properties need to be evaluated.
Object.keys()Only returns its own property key (
key):
let simpleColors = { colorA: 'white', colorB: 'black' }; let natureColors = { colorC: 'green', colorD: 'yellow' }; Object.setPrototypeOf(natureColors, simpleColors); Object.keys(natureColors); // => ['colorC', 'colorD'] natureColors['colorA']; // => 'white' natureColors['colorB']; // => 'black'
Object.keys( natureColors) Returns the
natureColors object itself and the enumerable property keys:
['colorC', 'colorD'].
natureColors Contains properties inherited from the
simpleColors prototype object. However, the
Object.keys() function skips them.
Object.values() and
Object.entries()Access the properties of an object using the same criteria: owned and enumerable properties. Let's take a look:
let simpleColors = { colorA: 'white', colorB: 'black' }; let natureColors = { colorC: 'green', colorD: 'yellow' }; Object.values(natureColors); // => ['green', 'yellow'] Object.entries(natureColors); // => [ ['colorC', 'green'], ['colorD', 'yellow'] ]
let simpleColors = { colorA: 'white', colorB: 'black' }; let natureColors = { colorC: 'green', colorD: 'yellow' }; let enumerableKeys = []; for (let key in natureColors) { enumerableKeys.push(key); } enumerableKeys; // => ["colorC", "colorD", "colorA", "colorB"]
enumerableKeys The array contains the keys for the natureColors object's own properties:
'colorC' and
'colorD'.
for...in traverses the property keys inherited from the
simpleColors prototype:
'colorA' and
' colorB'.
Object.values(), let us first look at getting the property value of the object before 2017 How is it achieved?
Object.keys() to collect the property keys, then use a property accessor and store the value in an extra variable. Let’s see an example:
let meals = { mealA: 'Breakfast', mealB: 'Lunch', mealC: 'Dinner' }; for (let key of Object.keys(meals)) { let mealName = meals[key]; // ... do something with mealName console.log(mealName); // => 'Breakfast' 'Lunch' 'Dinner' }
meals
是一个普通的JavaScript对象。使用Object.keys(meals)
和for...of
的循环枚举出对象键值。代码看起来很简单,但是可以通过去掉let mealName = meals[key]
来优化它。
通过使用Object.values()
可以直接访问对象属性值,可以实现优化。优化代码后如下:
let meals = { mealA: 'Breakfast', mealB: 'Lunch', mealC: 'Dinner' }; for (let mealName of Object.values(meals)) { console.log(mealName); // => 'Breakfast' 'Lunch' 'Dinner' }
由于Object.values(meals)
返回数组中的对象属性值,因此通过for...of
循环把对象的属性值直接分配给mealName
,因此不需要添加额外的代码,就像前面的例子那样。
Object.values()
只做一件事,但做得很好。这也是我们写代码的正确姿势。
Object.entries()返回属性值和键
Object.entries()
很强大,它返回对象的键和属性值,而且它们是成对的,比如: [ [key1, value1], [key2, value2], ..., [keyN, valueN] ]
。
可能直接使用有些不爽。幸运的是,数组在for...of
循环中传入let [x, y] = array
,很容易得到对应的访问键和值。
下面是Object.entries()
的示例:
let meals = { mealA: 'Breakfast', mealB: 'Lunch', mealC: 'Dinner' }; for (let [key, value] of Object.entries(meals)) { console.log(key + ':' + value); // => 'mealA:Breakfast' 'mealB:Lunch' 'mealC:Dinner' }
Object.entries(meals)
返回meal对象的属性键和值到一个数组中。然后通过for...of
循环解构性参数let [key, value]
把数组中的值分配给key
和value
变量。
正如所见,访问的键和值现在已经是一种舒适而且易于理解的形式。由于Object.entries()
返回一个与数组解构性赋值相兼容的集合,因此没有必要添加额外的赋值或声明行。
Object.entries()
将普通对象导入到Map
时是有用的。由于Object.entries()
返回Map
构造函数所接受的格式:key
和value
成对。因此问题变得无关紧要。
让我们创建一个JavaScript对象并将其导出到Map
中:
let greetings = { morning: 'Good morning', midday: 'Good day', evening: 'Good evening' }; let greetingsMap = new Map(Object.entries(greetings)); greetingsMap.get('morning'); // => 'Good morning' greetingsMap.get('midday'); // => 'Good day' greetingsMap.get('evening'); // => 'Good evening'
new Map(Object.entries(greetings))
构造函数使用一个参数来调用,这个参数是greeting
对象中导出的数组的一个键值对。
如预期的那样,map
实例greetingsMap
包含greetings
对象导入的属性。可以使用.get(key)
方法访问这些数据。
有趣的是,Map
提供了与Object.values()
和Object.entries()
方法相同的方法(只有它们返回迭代器),以便提取Map
实例的属性值或键值对:
Map.prototype.values()
等价于Object.values()
Map.prototype.entries()
等价于Object.entries()
Map
提供了普通对象的改良版。你可以获得Map
的大小(对于一个简单的对象,你必须手动操作),并使它作为键或对象类型(简单对象把键当作一个字符串原始类型)。
我们来看看map
的.values()
和.entries()
方法返回什么:
let greetings = { morning: 'Good morning', midday: 'Good day', evening: 'Good evening' }; let greetingsMap = new Map(Object.entries(greetings)); [...greetingsMap.values()]; // =>['Good morning', 'Good day', 'Good evening'] [...greetingsMap.entries()]; // =>[['morning','Good morning'], ['midday','Good day'],['evening','Good evening']]
注意:greetingsMap.values()
和greetingsMap.entries()
返回迭代器对象(Iterator Objects)。将结果放入一个数组,扩展运算符...
是必要的。在for...of
循环语句中可以直接使用迭代器。
关于顺序上的笔记
JavaScript对象是简单的键值映射。所以对象的属性的顺序是无关紧要的。在大多数情况下,你不应该依赖它。
然而,ES2015已经对迭代的方式提供了标准化的要求:首先是有序的数字字符,然后是插入顺序的字符串,然后是插入顺序的符号(symbols
)。在ES5和较早的标准中,属性的顺序没有指定。
如果你需要一个有序的集合,推荐的方法是将数据存储到数组或集合中。
总结
Object.values()
和Object.entries()
是为JavaScript开发人员提供函数的另一个改进步骤的新标准化 。
Object.entries()
Best executed with data group destructuring parameters so that keys and values can be easily assigned to different variables. This function also makes it easy to export normal JavaScript object properties into Map
objects. Map
can better support traditional map
(or hash
) behavior.
Note: object.values()
and object.entries()
The order in which data is returned is undetermined. So don't rely on the order.
English original address: https://dmitripavlutin.com/how-to-iterate-easily-over-object-properties-in-javascript/
Translation address: https: //www.w3cplus.com/javascript/how-to-iterate-easily-over-object-properties-in-javascript.html
For more programming-related knowledge, please visit: Introduction to programming! !
The above is the detailed content of Introduction to methods of traversing object properties in JS. 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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.

Java is a popular programming language with powerful file handling capabilities. In Java, traversing a folder and getting all file names is a common operation, which can help us quickly locate and process files in a specific directory. This article will introduce how to implement a method of traversing a folder and getting all file names in Java, and provide specific code examples. 1. Use the recursive method to traverse the folder. We can use the recursive method to traverse the folder. The recursive method is a way of calling itself, which can effectively traverse the folder.

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

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
