惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 【当耐特】
WordPress大学
WordPress大学
T
The Exploit Database - CXSecurity.com
博客园_首页
MyScale Blog
MyScale Blog
The Cloudflare Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
美团技术团队
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
M
MIT News - Artificial intelligence
Microsoft Security Blog
Microsoft Security Blog
F
Full Disclosure
V
V2EX
博客园 - Franky
博客园 - 三生石上(FineUI控件)
Hugging Face - Blog
Hugging Face - Blog
P
Proofpoint News Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
SecWiki News
SecWiki News
N
Netflix TechBlog - Medium
S
Secure Thoughts
酷 壳 – CoolShell
酷 壳 – CoolShell
Hacker News: Ask HN
Hacker News: Ask HN
爱范儿
爱范儿
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Webroot Blog
Webroot Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Martin Fowler
Martin Fowler
PCI Perspectives
PCI Perspectives
S
Security @ Cisco Blogs
Recorded Future
Recorded Future
Help Net Security
Help Net Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
AI
AI
Microsoft Azure Blog
Microsoft Azure Blog
K
Kaspersky official blog
G
GRAHAM CLULEY
H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
CERT Recently Published Vulnerability Notes
U
Unit 42
T
Tor Project blog
Cloudbric
Cloudbric
Hacker News - Newest:
Hacker News - Newest: "LLM"
MongoDB | Blog
MongoDB | Blog
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
Security Latest
Security Latest
N
News and Events Feed by Topic
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
How to Iterate Easily Over Object Properties in JavaScript
Dmitri Pavlutin · 2016-08-23 · via Dmitri Pavlutin Blog

In the same period of ECMAScript 2016 released in June 2016, JavaScript developers are happy to know that another bunch of awesome proposals reached the stage 4 (finished).

Let's list these features:

The new proposals are included in the ECMAScript 2017 standard, which probably will be released in the summer of 2017. Notice that the list of features may grow until that time. That's great!

Of course, you don't have to wait for ES2017 release or until the new features are implemented by vendors! Babel already contains most of these finished proposals.

This article is focused on how to improve the iteration over object properties:

  • To get properties values using Object.values()
  • To get properties key/value pairs using Object.entries()

At first sight, these static functions don't seem to add significant value. But when they're combined with destructuring assignments and for..of loops, you get a short and sweet way to iterate over object's properties.
Let's dive in.

1. Own and enumerable properties

As you might know already, Object.keys() accesses only the object's own and enumerable properties. It is reasonable since most of the times only these kinds of properties need evaluation.

Let's see an example when an object has own and inherited properties. Object.keys() returns only 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'


Object.keys(natureColors) returns own and enumerable property keys of the natureColors object: ['colorC', 'colorD'].
natureColors contains the properties inherited from simpleColors prototype object. However Object.keys() function skips them.

Object.values() and Object.entries() access object's properties by the same criteria: own and enumerable properties. Let's take a look:


// ...

Object.values(natureColors);

// => ['green', 'yellow']

Object.entries(natureColors);

// => [ ['colorC', 'green'], ['colorD', 'yellow'] ]


Now notice the difference from for..in loop statement. The loop iterates over enumerable, own and inherited properties. The following example illustrates that:


// ...

let enumerableKeys = [];

for (let key in natureColors) {

enumerableKeys.push(key);

}

enumerableKeys; // => ['colorC', 'colorD', 'colorA', 'colorB']


enumerableKeys array contains natureColors own properties keys: 'colorC' and 'colorD'.
Additionally for..in iterated over the property keys inherited from simpleColors prototype object: 'colorA' and 'colorB'.

2. Object.values() returns property values

To distinguish the benefits of Object.values() usage, let's see how to get an object's property values in a pre-ES2017 way.

First, the property keys are collected with Object.keys(). Then a property accessor is used and the value is stored in an additional 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 is a regular plain JavaScript object. The object keys are taken using Object.keys(meals) and in a for..of loop enumerated.
The code looks pretty simple, however, it can be optimized by removing the line let mealName = meals[key].

The optimization is possible by applying direct access to object property values using Object.values(). Now the property accessor line can be removed:


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 object property values in an array, the whole task reduces to a compact for..of loop. mealName is assigned directly in the loop, so there is no need for the additional line like it was in the previous example.

Object.values() does one thing, but does it well. This is a true path to clean code.

3. Object.entries() returns pairs of property values and keys

Object.entries() goes beyond and returns an array of object's property values and keys in pairs: [ [key1, value1], [key2, value2], ..., [keyN, valueN] ].

Probably it's not comfortable to use these pairs directly. Fortunately the array destructuring assignment let [x, y] = array in a for..of loop makes it really easy to access the key and value.

The following example shows Object.entries() in action:


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) returns meal object's pairs of keys and values in an array.
On the left side of for..of loop, the array destructuring assignment let [key, value] assigns key and value variables.

As seen, accessing keys and values has now a comfortable and easy to understand form. No additional lines for assignments or declarations are necessary since the Object.entries() returns a collection compatible with the array destructuring assignment.

Object.entries() is helpful when a plain object should be imported into a Map. The problem becomes trivial to solve because Object.entries() returns a format exactly that Map constructor accepts: key and value pairs.

Let's create a JavaScript object and export it into a 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)) constructor is invoked with an argument that is an array of key and value pairs, exported from greetings object.
As expected the map instance greetingsMap contains properties imported from greetings object. These can be accessed using .get(key) method.

Interestingly that Map provides equivalent to Object.values() and Object.entries() methods (only that they return Iterators), in order to extract property values or key-value pairs for a map instance:

Maps are an improved version of plain objects. You can get the size of a map (for a plain object you have to do it manually) and use as key any object type (plain object uses as key a string primitive type).

Let's see what return .values() and .entries() map's methods:


// ...

[...greetingsMap.values()];

// => ['Good morning', 'Good day', 'Good evening']

[...greetingsMap.entries()];

// => [ ['morning', 'Good morning'], ['midday', 'Good day'],

// ['evening', 'Good evening'] ]


Notice that greetingsMap.values() and greetingsMap.entries() return iterator objects. To put the result into an array, the spread operator ... is necessary.
In a for..of loop statement the iterator can be used directly.

4. A note on ordering

JavaScript objects are simple key-value maps. So the order of properties in the object is insignificant. You should not rely on it in most cases.

However ES2015 has standardized the way properties are iterated: first, come ordered number strings, then strings by insert order and then symbols by insert order. In ES5 and earlier standards, the order of properties is simply not specified.

If you need an ordered collection, storing data into an Array or Set is the recommended way.

5. Conclusion

Object.values() and Object.entries() are another improvement step for providing JavaScript developers with new standardized helper functions.

Object.entries() works best with array destructuring assignments, in a way that key and value are assigned to different variables easily. This function also makes easy to export plain JavaScript object properties into a Map object. Maps have better support of the traditional map (or hash) behavior.

Notice that the order in which Object.values() and Object.entries() return data is undetermined. So do not rely on the order.

I hope you enjoyed the reading! If so, feel free to share the post and write your opinion about these features in the comments below!