Home > Web Front-end > JS Tutorial > body text

Introduction to methods of traversing object properties in JS

青灯夜游
Release: 2020-11-26 17:44:51
forward
4195 people have browsed it

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:

The new proposal is included in the ESMAScript2017 standard to be released in 2017, probably in the summer of 2017. Please note that this feature list may keep growing. Very good!

Of course, you don’t have to wait until ES2017 is released, or until the vendor (browser) implements the new features!

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 attributeskey/value

At first glance, these static functions do not seem to Bring significant value. But when they are used in conjunction with a

for...of loop, you get a simple and beautiful way of traversing the properties of an object.

Let’s find out.

Own and enumerable properties

As you may already know,

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.

Let's look at an example of an object owning and inheriting properties.

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

Introduction to methods of traversing object properties in JS

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

Introduction to methods of traversing object properties in JS

Now please note the difference from for...in. Loops over the enumerable's own and inherited properties. The following example illustrates this:

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

Introduction to methods of traversing object properties in JS

enumerableKeys The array contains the keys for the natureColors object's own properties: 'colorC' and 'colorD'.

Additionally,

for...in traverses the property keys inherited from the simpleColors prototype: 'colorA' and ' colorB'.

Object.values() returns the property value

In order to distinguish the benefits of

Object.values(), let us first look at getting the property value of the object before 2017 How is it achieved?

First use

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

Introduction to methods of traversing object properties in JS

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

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

Object.entries(meals)返回meal对象的属性键和值到一个数组中。然后通过for...of循环解构性参数let [key, value]把数组中的值分配给keyvalue变量。

正如所见,访问的键和值现在已经是一种舒适而且易于理解的形式。由于Object.entries()返回一个与数组解构性赋值相兼容的集合,因此没有必要添加额外的赋值或声明行。

Object.entries()将普通对象导入到Map时是有用的。由于Object.entries()返回Map构造函数所接受的格式:keyvalue成对。因此问题变得无关紧要。

让我们创建一个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'
Copy after login

Introduction to methods of traversing object properties in JS

new Map(Object.entries(greetings))构造函数使用一个参数来调用,这个参数是greeting对象中导出的数组的一个键值对。

如预期的那样,map实例greetingsMap包含greetings对象导入的属性。可以使用.get(key)方法访问这些数据。

有趣的是,Map提供了与Object.values()Object.entries()方法相同的方法(只有它们返回迭代器),以便提取Map实例的属性值或键值对:

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

Introduction to methods of traversing object properties in JS

注意: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!

source:w3cplus.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template