Javascript 我在react中有数组的平面状态,我想将它设为嵌套数组,并将其推送到另一个对象的平面状态

Javascript 我在react中有数组的平面状态,我想将它设为嵌套数组,并将其推送到另一个对象的平面状态,javascript,reactjs,Javascript,Reactjs,我在一个反应组分中有两种状态 class ProductsideBar extends Component { constructor(props){ super(props) this.state = { Catgeory: [ {id:'1' , name:'parent_1' , parentId:'0'}, {id:'2' , name:

我在一个反应组分中有两种状态

    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做任何事情。

您可以这样做。我还没有包括查找子类别的逻辑,这很容易,但这一行代码应该会有所帮助

编辑:添加了正确的解决方案

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;
         })
    }
) 
和的可能副本
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;
         })
    }
)