Original text: dmitripavlutin.com/how-to-iter…

Translator: Front-end wisdom

Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.

Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.

Self enumerable properties

The object.keys () method returns an array of the given Object’s own enumerable properties, in order of their names and using the for… The in loop returns the same order as it iterates through the object. If the key-value of an object is not enumerable, an array of keys is returned.

This makes sense, because most of the time you only care about the properties of the object itself.

Let’s look at an example of an Object that has its own and inherited properties, object.keys () returns only its own property keys:

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 the code

The object.setProtoTypeof () method sets the Prototype of a specified Object (that is, the internal [[Prototype]] property) to another Object or null.

Keys (natureColors) Returns the natureColors Object’s own enumerable property key: [‘colorC’, ‘colorD’].

NatureColors contains attributes inherited from simpleColors prototype objects, but the object.keys () function skips them.

Object.values() and object.entries () are also arrays of key-value pairs that return a given Object’s own enumerable properties

// ...
Object.values(natureColors); 
// => ['green', 'yellow']
Object.entries(natureColors);
// => [ ['colorC', 'green'], ['colorD', 'yellow'] ]
Copy the code

Now pay attention to the relation with for.. In statement, for.. In can iterate through not only its own properties but also properties in the stereotype chain

// ...
let enumerableKeys = [];
for (let key in natureColors) {
  enumerableKeys.push(key);
}
enumerableKeys; // => ['colorC', 'colorD', 'colorA', 'colorB']
Copy the code

The array enumerableKeys contains natureColors’ own property keys: ‘colorC’ and ‘colorD’.

In addition the for… In also iterates over properties inherited from the simpleColors prototype object

2. Object.values() returns the attribute value

The ** object.values ()** method returns an array of all the enumerable property values of a given Object itself, in the same order as the values used for… The in loop has the same order (the difference is that for-In loops enumerate properties in the stereotype chain).

Keys () is used to collect keys and fetch the corresponding value from the Object:

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 the code

Meal is a common object. Use object.keys (meals) and enumerated for.. The of loop retrieves the object key.

The code looks simple, but let mealName = meals[key] is not necessary and can be further optimized as follows:

let meals = {
  mealA: 'Breakfast',
  mealB: 'Lunch',
  mealC: 'Dinner'
};
for (let mealName of Object.values(meals)) {
  console.log(mealName);
}
// 'Breakfast' 'Lunch' 'Dinner'
Copy the code

Because Object.values(meals) returns the Object attribute value in the array, it can be used directly in the for.. Simplified in of. MealName is assigned directly in the loop.

Object.entries()

The ** object.entries ()** method returns an array of key-value pairs for the given Object’s own enumerable properties, arranged in the same order as for… The in loop returns the same order as it iterates through the object (the difference is that for-In loops also enumerate properties in the prototype chain).

Object.entries() returns an array of key-value pairs such as [[key1, value1], [key2, value2],…, [keyN, valueN]].

It may not be convenient to use these key-value pairs directly, but it is very easy to access the keys and values through array deconstruction assignment, as shown below:

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 the code

As shown above, because Object.entries() returns a collection that is compatible with array deconstruction assignments, there is no need to add additional lines for assignments or declarations.

Object.entries() is useful when ordinary objects are being converted to maps because the format returned by Object.entries() is exactly the same as the format accepted by the Map constructor: key,value.

A two-dimensional array of key-value pairs can be converted into a Map object using the regular Map constructor.

Here’s a slow example:

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 the code

Map objects hold key-value pairs. Any value (object or raw value) can be a key or a value.

Interestingly, Map provides methods equivalent to Object.values() and object.entries () (except that they return Iterators) to extract attribute values or key-value pairs for Map instances:

  • Map.prototype.values() equivalent to object.values ()

  • Map.prototype.entries() equivalent to object.entries ()

A map is a modified version of a normal object, and you can get the size of the map (for normal objects, you must get it manually) and use any object type as a key (normal objects use string primitive types as keys).

Let’s look at the map method that returns.values () and.entries () :

// ...
[...greetingsMap.values()];
// => ['Good morning', 'Good day', 'Good evening']
[...greetingsMap.entries()];
// => [ ['morning', 'Good morning'], ['midday', 'Good day'], 
//      ['evening', 'Good evening'] ]
Copy the code

Note that greetingsmap.values () and greetingsmap.entries () return iterator objects. To put the result into an array, extend the operator… Is necessary.

The order of object attributes

JS objects are simple key-value mappings, so the order of attributes in an object is trivial and should not be relied upon in most cases.

In ES5 and earlier standards, the order of attributes was not specified at all.

However, starting with ES 6, the order of attributes is based on a special rule, unless specifically sorted by time. By two new methods Object. GetOwnPropertyNames and Reflect ownKeys to write the examples of this attribute collation.

  • Number: When the type of the attribute is a number type, it is sorted in order of the number from largest to smallest.
  • String: When the attribute type is string, it is sorted in chronological order.
  • Symbol: When the attribute type is Symbol, it is sorted in chronological order.

If ordered collections are required, it is recommended to store the data in arrays or sets.

conclusion

Object.values() and object.entries () are another step towards providing new standardized helper functions for JS developers.

Object.entries() is best used for array deconstruction by easily assigning keys and values to different variables. This function also makes it easy to Map pure JS object properties to Map objects. ,

Note that the order in which object.values () and object.entries () return data is uncertain, so do not rely on this method.

The bugs that may exist after code deployment cannot be known in real time. In order to solve these bugs, I spent a lot of time on log debugging. Incidentally, I recommend a good BUG monitoring tool for youFundebug.

communication

This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.