如何控制reactjs
中的循环?我只是希望如果标签或 Group
相等,则不会显示
generateAvailableOptions(data){
const availableGroups = [];
data.map(function(food){
availableGroups.push({
label: food.Group,
options: [
{ value: 'canAdd'+food.groupsid, label: food.description}
],
})
});
this.setState({availableGroups: availableGroups})
}
实际结果
Vegetables:
Carrots
Vegetables:
Cabbage
Vegetables:
Potato
Fruits:
Mango
Fruits:
Apple
Fruits:
Pineapple
这就是我想要的结果:
Vegetables:
Carrots
Cabbage
Potato
Fruits:
Mango
Apple
Pineapple
最佳答案
代码如下:
const data = [
{Group:'vegetable',description:'Carrots',groupsid:1},
{Group:'vegetable',description:'Cabbage',groupsid:1},
{Group:'vegetable',description:'Potato',groupsid:1},
{Group:'fruit',description:'Mango',groupsid:2},
{Group:'fruit',description:'Apple',groupsid:2}
]
generateAvailableOptions(data){
const result = data.reduce((item,curr)=> {
if(!item[curr.Group]) item[curr.Group] = [];
item[curr.Group].push({value: 'canAdd'+curr.groupsid, label: curr.description});
return item;
},{});
const availableGroups = [];
Object.entries(result).forEach(entry => {
const [key, value] = entry;
availableGroups.push({
"label":key,
"options": value
})
});
this.setState({availableGroups: availableGroups});
}
您可以看到结果:https://es6console.com/krhjx0rz/
关于javascript - Reactjs if 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68508232/