3

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,
        });
    })

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

You're awesome, Thanks!
0

Use Object.entries and .map:

const input = {
  key1:{ firstname: 'john', lastname: 'doe'}, 
  key2:{ firstname: 'david', lastname: 'smith'},
}
const transformed = Object.entries(input).map(([key, obj]) => Object.assign(obj, { ID: key }));
console.log(transformed);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.