Search code examples
javascriptecmascript-6lodash

How to push object literals as key-value pairs to array?


What is the best way to separate each pairs into array?

const myObject = {
  firstName: 'John',
  surname: 'Doe',
  city: 'New York'
}

to:

[{'firstName': 'John'}, {'surname': 'Doe'}, {'city': 'New York'}]

Btw, old posts suggest lodash mapping

const newArray = _.map(myObject, (value, key) => ({key, value}))

but it would return something like:

[ { key: 'firstName', value: 'John' },
 { key: 'surname', value: 'Doe' },
 { key: 'city', value: 'New York' } ]

I don't want the keys to be there.


Solution

  • You can achieve the required result using plain JS:

    Object.keys(myObject).map(key => ({[key]: myObject[key]}));
    

    This approach uses computed property names of ES2015.

    As suggested in comments, you can use Object.entries as well:

    Object.entries(myObject).map(([p, v]) => ({[p]: v}))
    

    If you want to use lodash anyway, you should surround key with square brackets:

    const newArray = _.map(myObject, (value, key) => ({[key], value}))