Search code examples
javascriptlodash

lodash convert Object of Objects to array of objects including key in it


sorry about poor explanation on the title.

basically i want to know if there's better way or shorter code to do my job. i recently started using lodash library.

so,

i have an object of objects like following.

   {
    key1:{ firstname: john, lastname: doe}, 
    key2:{ firstname: david, lastname: smith},
   }

eventually i wanna make them as following array of objects.

   [
    {ID: key1, firstname: john, lastname: doe },
    {ID: key2, firstname: david, lastname: smith}
   ]

and this is what i did.

const ArrayOfObjects = [];
    _.each(ObjectsOfObjects, (value, key) => {
        ArrayOfObjects.push({
            UID: key,
            ...value,
        });
    })

Solution

  • Lodash's _.map() can iterate objects. The 2nd param passed to the iteratee function is the key:

    const input = {
      key1:{ firstname: 'john', lastname: 'doe'}, 
      key2:{ firstname: 'david', lastname: 'smith'},
    }
    
    const result = _.map(input, (v, UID) => ({ UID, ...v }))
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>