In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces the ways of easily traversing object properties in JS. It is very detailed and has a certain reference value. Friends who are interested must read it!
1. Self-enumerable attributes
The Object.keys () method returns an array of enumerable properties of a given object in the same order that property names are returned when traversing the object using a for...in loop. If the key-value of an object cannot be enumerated, an array of keys is returned.
This is reasonable because most of the time you only need to focus on the properties of the object itself.
Looking at an example where an object has its own and inherited properties, Object.keys () returns only its own property 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'
The Object.setPrototypeOf () method sets the prototype of a specified object (that is, the internal [[Prototype]] property) to another object or null.
Object.keys (natureColors) returns the natureColors object's own enumerable property key: ['colorC','colorD'].
NatureColors contains properties inherited from the simpleColors prototype object, but the Object.keys () function skips them.
Object.values () and Object.entries () are also an array of key-value pairs that return enumerable properties of a given object itself.
/ /... Object.values (natureColors); / / = > ['green',' yellow'] Object.entries (natureColors); / / > [['colorC',' green'], ['colorD',' yellow']]
Now note the difference from the for..in statement. For..in can enumerate not only its own properties but also those in the prototype chain.
/ /... let enumerableKeys = []; for (let key in natureColors) {enumerableKeys.push (key);} enumerableKeys; / / = > ['colorC',' colorD', 'colorA',' colorB']
The enumerableKeys array contains the natureColors's own property keys: 'colorC' and' colorD'.
In addition, for..in also traverses properties inherited from the simpleColors prototype object
2. Object.values () returns the attribute value
The * * Object.values () * * method returns an array of all enumerable property values of a given object itself in the same order as using the for...in loop (the difference is that the for-in loop enumerates the attributes in the prototype chain).
For example, use Object.keys () to collect keys, and then use key to go to the object to get the corresponding value:
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'
Meal is a normal object. Use Object.keys (meals) and the enumerated for..of loop to get the object key value.
The code looks simple, but let mealName = meals [key] is not much 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'
Because Object.values (meals) returns the value of object attributes in the array, it can be simplified directly in for..of. MealName assigns values directly in the loop.
3. Object.entries ()
The Object.entries () method returns an array of key-value pairs of enumerable properties of a given object itself, in the same order as when traversing the object using the for...in loop (the difference is that the for-in loop also enumerates the attributes in the prototype chain).
Object.entries () returns a key-value pair array, 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 keys and values through array deconstruction assignments, 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'
As shown above, because Object.entries () returns a collection that is compatible with array deconstruction assignments, there is no need to add additional rows to the assignment or declaration.
Object.entries () is useful when ordinary objects are converted to Map, because the format returned by Object.entries () is exactly the same as the format accepted by the Map constructor: (key,value).
Using the regular Map constructor, you can convert a 2D key-value pair array into a Map object.
Let me give you an example to slow people down:
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'
The Map object holds key-value pairs. Any value (object or original value) can be used as a key or a value.
Interestingly, Map provides methods equivalent to Object.values () and Object.entries () (except that they return Iterators) to extract property values or key-value pairs for Map instances:
Map.prototype.values () is equivalent to Object.values ()
Map.prototype.entries () is equivalent to Object.entries ()
Map is an improved version of normal objects that can get the size of the map (for normal objects, you must get it manually) and use any object type as the key (normal objects use the string primitive type as the key).
Let's look at the method that returns the map of .values () and .values ():
/ /. [... greetingsMap.values ()]; / / = > ['Good morning',' Good day', 'Good evening'] [... greetingsMap.entries ()]; / / > [[' morning', 'Good morning'], [' midday', 'Good day'], / / [' evening', 'Good evening']]
Note: reetingsMap.values () and greetingsMap.entries () return iterator objects. To put the result in an array, extend the operator. It's necessary.
4. The order of object attributes
The JS object is a simple key-value mapping, so the order of attributes in the object is trivial, and in most cases, you should not rely on it.
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. Write an example to illustrate this property collation through two new methods, Object.getOwnPropertyNames and Reflect.ownKeys.
Numbers: when the type of an attribute is a numeric type, it is sorted according to the order of the number from largest to smallest.
String: when the type of the attribute is a string, it is sorted in chronological order
Symbol: when the attribute is of type Symbol, it is sorted in chronological order.
If you need ordered collections, it is recommended that you store the data in an array or Set.
Summary:
Object.values () and Object.entries () are another improvement step in providing new standardized helper functions for JS developers.
Object.entries () is best suited for array deconstruction assignments by easily assigning keys and values to different variables. This function can also easily map pure JS object properties to Map objects. 、
Note: the order in which Object.values () and Object.entries () return data is uncertain, so don't rely on it.
The BUG that may exist after the code deployment cannot be known in real time. In order to solve these BUG, we spent a lot of time debugging log. By the way, we recommend a useful BUG monitoring tool, Fundebug.
These are all the contents of the article "what are the easy ways to traverse object properties in JS?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.