Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
The Keys and values method in Javascript
JavaScript provides several methods to extract keys and values from objects and Maps. The most common approaches are Object.keys(), Object.values() for plain objects, and the keys(), values() methods for ES6 Maps.
Getting Keys from Objects
Use Object.keys() to extract all property names from an object as an array:
const myObject = {
key1: "value1",
key2: "value2",
key3: "value3"
};
const keys = Object.keys(myObject);
console.log(keys);
[ 'key1', 'key2', 'key3' ]
Getting Values from Objects
Object.values() extracts all property values from an object:
const myObject = {
key1: "value1",
key2: "value2",
key3: "value3"
};
const values = Object.values(myObject);
console.log(values);
[ 'value1', 'value2', 'value3' ]
Using ES6 Map Methods
ES6 Maps provide built-in keys() and values() methods that return iterators:
const myMap = new Map([
["key1", "value1"],
["key2", "value2"],
["key3", "value3"]
]);
// Getting keys iterator
console.log(myMap.keys());
// Converting to array
console.log(Array.from(myMap.keys()));
// Getting values iterator
console.log(myMap.values());
// Converting values to array
console.log(Array.from(myMap.values()));
[Map Iterator] { 'key1', 'key2', 'key3' }
[ 'key1', 'key2', 'key3' ]
[Map Iterator] { 'value1', 'value2', 'value3' }
[ 'value1', 'value2', 'value3' ]
Custom Implementation Example
For custom data structures, you can implement similar methods:
class MyMap {
constructor() {
this.container = {};
}
put(key, value) {
this.container[key] = value;
}
keys() {
return Object.keys(this.container);
}
values() {
return Object.values(this.container);
}
}
const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");
console.log("Keys:", myMap.keys());
console.log("Values:", myMap.values());
Keys: [ 'key1', 'key2' ] Values: [ 'value1', 'value2' ]
Comparison
| Method | Return Type | Use Case |
|---|---|---|
Object.keys() |
Array | Plain objects |
Object.values() |
Array | Plain objects |
Map.keys() |
Iterator | ES6 Maps |
Map.values() |
Iterator | ES6 Maps |
Conclusion
Use Object.keys() and Object.values() for plain objects, and Map's keys()/values() methods for ES6 Maps. Convert Map iterators to arrays using Array.from() when needed.
Advertisements
