Search code examples
reactjslistreact-statereact-class-based-component

How to iterate and display each element from inner list - reactjs


How to iterate and display each element from 'grandChildren' list -> for eg: ["AQ11", "AS12"]. Thank you.

responseData:

[{Key:"A",Value:["AQ11", "AS12"]}, {Key:"C",Value:["CN22", "CL33", "CV44"]}].

Have set KeyValuePair's key to 'children' and Value to 'grandChildren' state.

I am able to display children but not grandChildren as it returns list of values ["AQ11", "AS12"]. Tried below but could not succeed

render() {
        const child= Object.values(this.state.items);
        const grandChild= Object.values(this.state.items[i].grandChildren); // Not sure how to set -  how do I pass value of i. 

        return (
            <div>

                    {child.map((element, index) => {
                    <div key={index + element.children}>
                    return (                                                                                     
                         <Autocomplete                           
                            value={element.children}        // this displays children like "A" OR "C"                                                
                         />
                 
                            {grandChild.map((element1, index) => (                                                                       
                                <Autocomplete                                                      
                                value={element.grandChildren[element1]}  // NOT SURE HOW TO GET THIS TO WORK                                                
                                />                        
                            ))}
                    </div>
                    ))} 

                    );
           </div>

How do I iterate and display value of grandchildren


Solution

  • You can do it like this

    render(){
      const child = Object.values(this.state.items);
    
      return (
        <div>
          {child.map((element, index) => {
            const grandChild = Object.values(this.state.items[index].grandChildren);
    
            return (
              <div key={index}>
                <Autocomplete
                  value={element.children} // this displays children like "A" OR "C"
                />
    
                {grandChild.map((element1, index) => (
                  <Autocomplete
                    value={element1} 
                  />
                ))}
              </div>
            );
          })}
        </div>
      );
    };