我已经和其他的答案核对过了,但没能解决我的问题。我尝试过很多事情,但最终在映射时出错了。这是我的主要数据列表示例。
连接= {mruCode:"1700",除法:“农业”,国家:“美国”,},{mruCode:"1000",除法:“农业”,国家:“加拿大”,},{mruCode:"1500",除法:“工业”,国家:“澳大利亚”,.}。
现在我想根据划分的划分方法将国家分组:“农业”国家:{“美国”,“加拿大”}。然后我要映射成组的列表。怎么做?这可能是类似的问题,但无法得到结果。
到目前为止,我已经尝试过了,但是在映射时会出现错误。
组件代码
render(){
const _labels = store.getLabels();
const {conLocations} = this.props;
const groups= _.groupBy(conLocations,'division');
console.log(groups);
return (
<table>
<tbody>
{this.props.groups.map(grp=>conLocations.filter(element=>grp.division.includes(element.division)).map((element,index)=>{
<tr key={index}>
<td>{_labels[element.division]}</td>
<td>{element.country}</td>
</tr>
}))}
</tbody>
</table>
);
}
在用户界面中,用户可以看到这样的->农业-美国,加拿大
发布于 2019-07-29 08:58:32
您只需按除法分组,然后将结果映射到所需的格式。
const groups = _(conLocations)
.groupBy('division')
.map((locations, division) => {
const country = locations.map(location => location.country);
return ({
division,
country,
})
})
.value();
以上代码将以这种格式返回结果。
[
{
division:'Agricultural',
country:[
'USA',
'CANADA'
]
},
{
division:'Industrial',
country:[
'AUSTRALIA'
]
}
]
发布于 2019-07-29 08:59:09
在存档中,_.groupBy
实际上创建了一个以分组参数作为键的对象,因此您必须将它作为一个对象来处理。
const conLocations = [{
mruCode: "1700",
division: "Agricultural",
country: "USA"
}, {
mruCode: "1000",
division: "Agricultural",
country: "CANADA"
}, {
mruCode: "1500",
division: "Industrial",
country: "AUSTRALIA"
}];
const groups = _.groupBy(conLocations, 'division');
Object.entries(groups).map(([key, value])=>{
console.log("key:", key, "\nvalue:", value)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
https://stackoverflow.com/questions/57250239
复制相似问题