[英]i have flat state of arrays in react and i want to make it nested array and push it to another object ins state
I have two states in a react component, 我在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:[];
}
....
I want a javascript function that changes state. 我想要一个可更改状态的JavaScript函数。 Category to something like this bellow nested array and add to state.nestedCategory ..
类别类似于此波纹管嵌套数组,然后添加到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'
}]
},
]
Then i can do anything with nestedCategory. 然后,我可以使用nestedCategory做任何事情。
You can do something like this. 你可以做这样的事情。 I haven't included the logic for finding the subcategory, that is easy but this one liner code should help.
我没有包括找到子类别的逻辑,这很简单,但是这一行代码应该会有所帮助。
Edit : Added a proper solution. 编辑:添加了适当的解决方案。
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;
})
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.