Reputation: 410
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,
});
})
Upvotes: 3
Views: 4573
Reputation: 193077
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>
Upvotes: 2
Reputation: 371168
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);
Upvotes: 0