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

推荐订阅源

Spread Privacy
Spread Privacy
K
Kaspersky official blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Forbes - Security
Forbes - Security
Hacker News - Newest:
Hacker News - Newest: "LLM"
The Last Watchdog
The Last Watchdog
SecWiki News
SecWiki News
Attack and Defense Labs
Attack and Defense Labs
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
S
Secure Thoughts
WordPress大学
WordPress大学
Microsoft Security Blog
Microsoft Security Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
Security Latest
Security Latest
TaoSecurity Blog
TaoSecurity Blog
Cyberwarzone
Cyberwarzone
S
SegmentFault 最新的问题
Cloudbric
Cloudbric
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
N
Netflix TechBlog - Medium
MyScale Blog
MyScale Blog
T
The Blog of Author Tim Ferriss
H
Hacker News: Front Page
C
Cybersecurity and Infrastructure Security Agency CISA
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
AWS News Blog
AWS News Blog
AI
AI
G
GRAHAM CLULEY
IT之家
IT之家
P
Privacy & Cybersecurity Law Blog
L
Lohrmann on Cybersecurity
Last Week in AI
Last Week in AI
D
Docker
Recent Announcements
Recent Announcements
O
OpenAI News
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
S
Security @ Cisco Blogs
T
Troy Hunt's Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
A
About on SuperTechFans
The Cloudflare Blog
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic

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? 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() 5 JavaScript Scope Gotchas
How to Access Object's Keys, Values, and Entries in JavaScript
Dmitri Pavlutin · 2020-08-11 · via Dmitri Pavlutin Blog

You often need to look through the properties and values of plain JavaScript objects.

Here are the common lists to extract from an object:

  • The keys of an object is the list of property names.
  • The values of an object is the list of property values.
  • The entries of an object is the list of pairs of property names and corresponding values.

Let's consider the following JavaScript object:


const hero = {

name: 'Batman',

city: 'Gotham'

};


The keys of hero are ['name', 'city']. The values are ['Batman', 'Gotham']. And the entries are [['name', 'Batman'], ['city', 'Gotham']].

Let's see what utility functions provide JavaScript to extract the keys, values, and entries from an object.

1. Object.keys() returns keys

Object.keys(object) is a utility function that returns the list of keys of object.

Let's use Object.keys() to get the keys of hero object:


const hero = {

name: 'Batman',

city: 'Gotham'

};

Object.keys(hero); // => ['name', 'city']


Object.keys(hero) returns the list ['name', 'city'], which, as expected, are the keys of hero object.

1.1 Keys in practice: detect if object is empty

If you'd like to quickly check if an object is empty (has no own properties), then a good approach is to check whether the keys list is empty.

To check if the object is empty, all you need to do is verify the length property of the array returned by Object.keys(object):


const isObjectEmpty = Object.keys(object).length === 0;


In the following example, empty has no properties, while nonEmpty object has one property:


const empty = {};

const nonEmpty = { a: 1 };

Object.keys(empty).length === 0; // => true

Object.keys(nonEmpty).length === 0; // => false


Object.keys(empty).length === 0 evaluates to true, which means that empty has no properties.

2. Object.values() returns values

Object.values(object) is the JavaScript utility function that returns the list of values of object.

Let's use this function to get the values of hero object:


const hero = {

name: 'Batman',

city: 'Gotham'

};

Object.values(hero); // => ['Batman', 'Gotham']


Object.values(hero) returns the values of hero: ['Batman', 'Gotham'].

2.1 Values in practice: calculate properties sum

books is an object that holds the prices of some books. The property key is the book name, while the value is the book price.

How would you determine the sum of all books from the object? By accessing the values of the object, and summing them.

Let's see how to do that:


const books = {

'The Shining': 5.50,

'Harry Potter and the Goblet of Fire': 10.00,

'1984': 4.35

};

const prices = Object.values(books);

prices; // => [4.35, 5.5, 10]

const sum = prices.reduce((sum, price) => sum + price);

sum; // => 19.85


Object.values(books) returns the values of books object, which in this case is the prices list.

Then prices.reduce(Math.sum) summarizes the prices.

3. Object.entries() returns entries

Finally, Object.entries(object) is an useful function to access the entries of object.

Let's extract the entries of hero object:


const hero = {

name: 'Batman',

city: 'Gotham'

};

Object.entries(hero); // => `[['name', 'Batman'], ['city', 'Gotham']]`


Object.entries(hero) returns the entries of hero: [['name', 'Batman'], ['city', 'Gotham']].

3.1 Entries in practice: find the property having 0 value

Again, let's use the books object that holds the prices of some books. This time, due to a mistake, one of the books has been assigned with the price 0.

Let's find the book with the price 0 and log its name to console.

Using the object's entries list fits well to solve this task:


const books = {

'The Shining': 5.50,

'Harry Potter and the Goblet of Fire': 10.00,

'1984': 0

};

for (const [book, price] of Object.entries(books)) {

if (price === 0) {

console.log(book);

}

}

// logs '1984'


Object.entries(books) returns a list of tuples: the book name and price. const [book, price] extracts in place from the tuple the book name and price.

Finally, inside the for..of cycle, you can check which book price is 0, and log the name to console if that's the case.

4. Summary

The keys, values, and entries are 3 common lists to extract from a JavaScript object for further processing.

JavaScript provides the necessary utility function to access these lists:

  • The keys are returned by Object.keys(object)
  • The values are returned by Object.values(object)
  • And the entries are returned by Object.entries(object)

What other ways to access keys, values, and entries do you know?