The Old County The Old County - 2 months ago 7
Javascript Question

Refactoring object into a flat array

I have an object like this.

{Brunch: 2, Kimchi: 1}


I need to refactor it into an an array/object

[{
"label" : "Brunch",
"value" : 2
},
{
"label" : "Kimchi",
"value" : 1
}]

Answer

You can use Object.keys() and map() to get desired result.

var obj = {
  Brunch: 2,
  Kimchi: 1
}

var result = Object.keys(obj).map(function(k) {
  return {
    "label": k,
    "value": obj[k]
  }
})

console.log(result)