0

I have two states in a react component,

    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. Category to something like this bellow nested array and add to 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.

zurebe-pieter
  • 3,246
  • 21
  • 38
  • Possible duplicate of [Create nested object from flat array](https://stackoverflow.com/questions/49974999/create-nested-object-from-flat-array) and [Hierarchical json from flat with parent ID](https://stackoverflow.com/questions/15376251) – adiga Feb 11 '19 at 19:09

1 Answers1

-1

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;
         })
    }
) 
Arpit Agrawal
  • 1,180
  • 1
  • 10
  • 21