Search code examples
javascriptarraysjsonjavascript-objects

How to transform dictionary in array of documents in JavaScript?


I have this following object:

var d = { 
  "restaurant": 20, 
  "hotel": 40, 
  "travel": 60 
}

And I need to transform it into this:

var a = [
{ 
  "category_name": "restaurant",
  "amount": 20
},
{ 
  "category_name": "hotel",
  "amount": 40
},
{ 
  "category_name": "travel",
  "amount": 60
}
]

This might be a silly question but as I am not a programmer I am facing this issue. Could some one help me at least pointing a direction for me to follow?


Solution

  • Try this

    Object.keys(d).map(k=>({"category_name": k, "amount": d[k]}))