DEV Community

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

Posted on

2 1

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)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay