Reputation: 5328
I want to map an array of objects and add a property to each item. At the moment the original values get nested. How can I change it to get an item with a flattened object?
import _ from 'lodash';
let arr = [{name: "tim"}, {name: "tom"}]
const id = {id: 1}
console.dir(_.map(arr, item => ({...id, item})));
result:
[ { id: 1, item: { name: 'tim' } },
{ id: 1, item: { name: 'tom' } } ]
wished result:
[ { id: 1, name: 'tim' },
{ id: 1, name: 'tom' } ]
Upvotes: 0
Views: 28
Reputation: 191986
Spread the item
as well:
let arr = [{name: "tim"}, {name: "tom"}]
const id = {id: 1}
console.dir(_.map(arr, item => ({ ...id, ...item })));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Or use _.merge()
with lodash/fp:
const mergeId = id => _.map(_.merge(id))
let arr = [{name: "tim"}, {name: "tom"}]
const id = {id: 1}
result = mergeId(id)(arr)
console.dir(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
Upvotes: 1