【问题标题】:i have flat state of arrays in react and i want to make it nested array and push it to another object ins state我在反应中有数组的平坦状态,我想让它嵌套数组并将其推送到另一个对象 ins 状态
【发布时间】:2019-07-05 08:19:15
【问题描述】:

我在一个反应​​组件中有两个状态,

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

【问题讨论】:

标签: javascript reactjs


【解决方案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;
         })
    }
) 

【讨论】:

    猜你喜欢
    • 2017-06-05
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2021-04-15
    相关资源
    最近更新 更多