Reputation: 13721
Can someone help me generate a new array of objects from an existing one using lodash? I've been trying a combination of _.zipObject and map
but to no avail... basically, I have an array of objects like:
const names = [
{
first_name: 'nedd',
given_name: 'cersei'
},
{
first_name: 'tyrion',
given_name: 'tywin'
}
]
However, I want it to look like:
[
{
name: 'nedd'
},
{
name: 'cersei'
},
{
name: 'tyrion'
},
{
name: 'tywin'
},
]
I have tried various iterations of:
const newArray = _.zipObject( names, _.fill( Array(names.length), {name: ['first_name' || 'given_name']} ) );
But without any luck... can someone help?
Thanks in advance!
Upvotes: 1
Views: 805
Reputation: 40584
Use _.flatMap
combined with _.map
:
_.flatMap(names, (nameObj) => _.map(nameObj, (objVal) => { return { name: objVal }; }));
Upvotes: 2
Reputation: 3651
This might work:
_.flatMap(names, (n)=> [{name: n.first_name}, {name: n.given_name}]);
Upvotes: 2