May 6, 2021

Converting Object to Array without losing keys

Let’s say we have a nested javascript Object, and we want to convert it in Array in a modern way. For example a list of Tarantino’s movies, rated by my unquestionable judgment:

var TarantinoMovies = { 
  1997: { name: 'Jackie Brown', star: 6 },
  2003: { name: 'Kill Bill 1', star: 10 },
  2004: { name: 'Kill Bill 2', star: 5 },
  2007: { name: 'Death Proof', star: 5 },
  2009: { name: 'Inglourious Basterds', star: 10 },
  2012: { name: 'Django Unchained', star: 9 },
  2015: { name: 'The Hateful Eight', star: 6 },
  2019: { name: 'Once Upon a Time in... Hollywood', star: 7 },
}

We can easily write:

let array = Object.values(TarantinoMovies)

console.log(array)
// [{ name: 'Jackie Brown', star: 6 }, { name: 'Kill Bill 1', star: 10 }..] 

But this way we lost the keys, which in our example are the year of the movie, therefore an important fact.

A pretty good solution might be:

let array = Object.keys(TarantinoMovies).map((key) => { 
    return { ...TarantinoMovies[key], year: key } 
})

console.log(array)
// [{ name: 'Jackie Brown', star: 6, year: '1997' }, { name: 'Kill Bill 1', star: 10, year: '2003' }.. ] 

Now we have converted the object and added a key/value pair to each object in the array.


Uma Turman and Lucy Liu in Kill Bill 1, Quentin Tarantino 2003

No copyright / do whatever the hell you want with these contents
Built with Hugo and Kiss theme. Hosted on Netlify. Icons made by Ddara