DEV Community

Cover image for Object.keys() in JavaScript
Oleg Chursin
Oleg Chursin

Posted on

Object.keys() in JavaScript

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' 
}
Enter fullscreen mode Exit fullscreen mode

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' }
//    ]
Enter fullscreen mode Exit fullscreen mode

Array of keys:

const keysArr = Object.keys(holidays).map(key => {
  return key;
}

// => [ 'NYE', 'XMAS' ]
Enter fullscreen mode Exit fullscreen mode

Array of values:

const valuesArr = Object.keys(holidays).map(key => {
  return holidays[key];
}

// => [ '2018-01-01', '2018-12-25' ]
Enter fullscreen mode Exit fullscreen mode

Keeping it short and simple. Till next time.

Top comments (0)