Transform flat object into array of single property objects

Viewed 22

What is the most succinct way in ES6+ to transform this:

{
  'key 1': 'value 1',
  'key 2': 'value 2',
  'key 3': 'value 3'
}

into this:

[
  { 'key 1': 'value 1' },
  { 'key 2': 'value 2' },
  { 'key 3': 'value 3' }
]
1 Answers

I would suggest using Object.entries(), then Array.Map(), along with some destructuring to transform the single object into an array of key / value pairs:

const obj = {
  'key 1': 'value 1',
  'key 2': 'value 2',
  'key 3': 'value 3'
}

const arr = Object.entries(obj).map(([key, value]) => ({ [key]: value }));
console.log('Result:', arr)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Another way to approach this is simply to use Object.keys(), then accessing each value using obj[key]:

const obj = {
  'key 1': 'value 1',
  'key 2': 'value 2',
  'key 3': 'value 3'
}

const arr = Object.keys(obj).map(key => ({ [key]: obj[key] }));
console.log('Result:', arr)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related