JavaScript – Array to Object and Object to Array Conversion

Array to Object conversion is a very important interview question and we need to do this almost every day. Here is my take on this problem. 

const desserts = ['cake','donut','chocolate','jelly','cupcake']
const dessertsObj = desserts.reduce(function(result, item, index, array) {
  result[index] = item
  return result
}, {}) 

When we have an object we can convert that to an array.

var desserts = {
  0: 'cake',
  1: 'donut',
  2: 'chocolate',
  3: 'jelly',
  4: 'cupcake'

var dessertsArray = Object.keys(desserts).map(function(k) {
    return [+k, desserts[k]]