我的react组件有两个状态
class ProductsideBar extends Component {
constructor(props){
super(props)
this.state = {
Catgeory: [
{id:'1' , name:'parent_1' , parentId:'0'},
{id:'2' , name:'child_1' , parentId:'1'},
{id:'3' , name:'child_2' , parentId:'1'},
{id:'4' , name:'parent_2' , parentId:'0'},
{id:'5' , name:'child_1' , parentId:'4'},
{id:'6' , name:'child_2' , parentId:'4'},
],
subCatgeory:[]
nestedCategory:[];
}
....
我想要一个更改状态的JavaScript函数。将其分类为下面这样的嵌套数组,然后添加到state.nestedCategory ..
nestedCategory: [
{
id:'1' ,
name:'parent_1' ,
parentId:'0',
subCategory: [{
id:'2' ,
name:'child_1',
parentId:'1'
}, {
id:'3' ,
name:'child_2' ,
parentId:'1'
}]
}, {
id:'4' ,
name:'parent_2' ,
parentId:'0',
subCategory: [{
id:'5' ,
name:'child_1',
parentId:'4'
}, {
id:'6' ,
name:'child_2' ,
parentId:'4'
}]
},
]
然后我可以使用nestedCategory做任何事情。
答案 0 :(得分:-1)
您可以执行以下操作。我没有包括找到子类别的逻辑,这很容易,但是这一行代码应该会有所帮助。
编辑:添加了适当的解决方案。
this.setState(
{
nestedCategory : this.state.category.map((value, index) => {
const nobj = {...value};
nobj.subCategory = this.state.subcategory.filter((value2) => value2.parentId === value.id);
return nobj;
})
}
)