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:Object.values()Get object properties
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()
很强大,它返回对象的键和属性值,而且它们是成对的,比如: [ [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!