我使用fetch和Flatlist从laravel rest获取和显示json数据,laravel api的api.my输出如下所示
[
{"teacher": "alex","student":"roger","class":"6"}
{"teacher": "alex","student":"simmon","class":"6"}
{"teacher": "alexandra","student":"henry","class":"8"}
....
]
在react原生中,我使用fetch api从laravel中获取数据,如下所示
fetch('http://11.1.1.1:8000/api/get_data/' {
method: 'get',
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({ record: responseJson.data})
})
.catch((error) => {
console.error(error);
});
在扁平列表中,我显示了这样的数据
<FlatList
data={this.state.record}
keyExtractor={(item, index) => index + ""}
ListHeaderComponent={this.tableHeader}
stickyHeaderIndices={[0]}
renderItem={
({item}) => (
<Text>{item.data.student}</Text>
<Text>{item.data.class}</Text>
)
}
/>
我的输出是这样的
sr.no student class
1 roger 6
2 simmon 6
3 henry 8
但是我想按老师的名字分组,我想要的输出是这样的
alex //teacher name
sr.no student class
1 roger 6
2 simmon 6
alexendra //teacher name
sr.no student class
1 henry 8
如何使用扁平列表中的reduce函数来实现这种输出?
发布于 2021-07-01 20:20:25
您可以构建自己的函数:
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
console.log(groupBy(this.state.record, 'teacher'))
或者,您可以使用外部库,如lodash:
https://stackoverflow.com/questions/68199751
复制相似问题