Object.keys() in JavaScript
Oleg Chursin
Posted on March 9, 2019
A quick note on what you can do with JavaScript’s Object.keys()
method.
We will use it to transform an Object
(dictionary
if you prefer some terminology clarity or hash
if you are coming from the world of Ruby) into an Array
with three different outputs:
1) creating an array of objects with reassigned key-value pairs,
2) creating and array of keys, and
3) creating an array of values.
Let’s start. Our initial object is a couple of US Federal Holidays with names as keys and dates as values:
const holidays = {
NYE: '2018-01-01',
XMAS: '2018-12-25'
}
Array of objects with redefined key-value pairs:
const holidaysArray = Object.keys(holidays).map(key =>
({
name: key,
date: holidays[key]
})
)
// => [
// { name: 'NYE', date: '2018-01-01' },
// { name: 'XMAS', date: '2018-12-25' }
// ]
Array of keys:
const keysArr = Object.keys(holidays).map(key => {
return key;
}
// => [ 'NYE', 'XMAS' ]
Array of values:
const valuesArr = Object.keys(holidays).map(key => {
return holidays[key];
}
// => [ '2018-01-01', '2018-12-25' ]
Keeping it short and simple. Till next time.
💖 💪 🙅 🚩
Oleg Chursin
Posted on March 9, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.