我正在写一小段JS代码,它有一个数组:
[
{ title: 'title1', id: 1 },
{ title: 'title1', id: 2 },
{ title: 'title2', id: 3},
{ title: 'title2', id: 4}
]
我需要这样的东西:
"queried": {
"title1": [1, 2],
"title2": [3, 4],
}
我试图用Lodash和_.groupBy(数组,“标题”)这样做,但我得到:
{
title1:[
{ title: 'title1', id: 1 },
{ title: 'title1', id: 2 }
],
title2:[
{ title: 'title2', id: 3 },
{ title: 'title2', id: 4 }
],
}
请问如何解决?
解决方法:
使用_.mapValues()
迭代组,使用_.map()
提取id的值:
const lol = [{"title":"title1","id":1},{"title":"title1","id":2},{"title":"title2","id":3},{"title":"title2","id":4}];
const result = _.mapValues(
_.groupBy(lol, 'title'),
v => _.map(v, 'id')
);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>