AHinson
AHinson

Reputation: 661

Turn object into array of objects

I'm trying to turn this object into an array of objects, with the object key being placed into a property of each of the objects in the array.

Here is the input:

var input = {
  "2017-03-13": ["Event 1", "Event 2"],
  "2017-03-14": ["Event 1", "Event 2"],
  "2017-03-15": ["Event 1", "Event 2"]
}

And here is my desired output:

[
  {
    date: "2017-03-13",
    events: ["Event 1", "Event 2"]
  },
  {
    date: "2017-03-14",
    events: ["Event 1", "Event 2"]
  },
  {
    date: "2017-03-15",
    events: ["Event 1", "Event 2"]
  }
]

Any thoughts on how I might approach this? I have underscore.js at my disposal as well.

Upvotes: -1

Views: 1017

Answers (3)

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can do this with Object.keys() and map().

var input = {
  "2017-03-13": ["Event 1", "Event 2"],
  "2017-03-14": ["Event 1", "Event 2"],
  "2017-03-15": ["Event 1", "Event 2"]
}

var result = Object.keys(input).map(function(e) {
  return {date: e, events: input[e]}
})

console.log(result)

With ES6 you can do this in one line using arrow functions.

var result = Object.keys(input).map(e => ({date: e, events: input[e]}))

Upvotes: 3

Brenton Klassen
Brenton Klassen

Reputation: 138

Object.keys(input).map(key => {
    date: key,
    events: input[key]
});

Upvotes: 6

Christos
Christos

Reputation: 53958

You could try something like this:

var input = {
  "2017-03-13": ["Event 1", "Event 2"],
  "2017-03-14": ["Event 1", "Event 2"],
  "2017-03-15": ["Event 1", "Event 2"]
}

var output = [];
for(var key in input){
    output.push({
      date: key,
      events: input[key]
    })
}

console.log(output);

Or in a more functional way:

var input = {
  "2017-03-13": ["Event 1", "Event 2"],
  "2017-03-14": ["Event 1", "Event 2"],
  "2017-03-15": ["Event 1", "Event 2"]
}

var output = Object.keys(input)
                   .map(function(key){
                       return { date: key, events: input[key]};
                   });
      
console.log(output);

Upvotes: 2

Related Questions