1 回答
TA贡献1815条经验 获得超6个赞
使用_.flatMap()让所有的数组subdata的项目,然后用_.uniqueBy()用subid:
const myArray = [{"_id":"1","subdata":[{"subid":"11","name":"A"},{"subid":"12","name":"B"}]},{"_id":"2","subdata":[{"subid":"12","name":"B"},{"subid":"33","name":"E"}]}];
const result = _.uniqBy(_.flatMap(myArray, 'subdata'), 'subid');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
使用 lodash/fp 您可以使用_.flow()相同的方法生成函数:
const fn = _.flow(
_.flatMap('subdata'),
_.uniqBy('subid')
);
const myArray = [{"_id":"1","subdata":[{"subid":"11","name":"A"},{"subid":"12","name":"B"}]},{"_id":"2","subdata":[{"subid":"12","name":"B"},{"subid":"33","name":"E"}]}];
const result = fn(myArray);
console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
添加回答
举报