如何防止lodash映射创建嵌套对象?

时间:2019-05-02 11:02:59

标签: lodash

我想映射对象数组并将属性添加到每个项目。此刻,原始值被嵌套。如何更改它以使对象具有展平的对象?

code example

import _ from 'lodash';

let arr = [{name: "tim"}, {name: "tom"}]
const id = {id: 1}

console.dir(_.map(arr, item => ({...id, item}))); 

结果:

[ { id: 1, item: { name: 'tim' } },
  { id: 1, item: { name: 'tom' } } ]

希望的结果:

[ { id: 1,  name: 'tim'  },
  { id: 1,  name: 'tom' } ]

1 个答案:

答案 0 :(得分:1)

也传播item

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>

或将_.merge()与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>