Home > Software design >  for of loop unable to loop through values of an object which has been treated as an array in reactjs
for of loop unable to loop through values of an object which has been treated as an array in reactjs

Time:02-26

The renderRow() is a method in a React class component which is to get key-values of the state operators object and pass the values of the object into a react component arithmeticComponent to be rendered but its unable to produce the values after calling a for loop upon each map on the key. the issue is the value of the object is unable to be passed as a prop into the arithmeticComponent

 state = {
        operators: {
          topOperators: ["C", "Mod", "<"],
          numbers: ["%", ".", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        },
      };




 renderRow() {
        {
          Object.entries(this.state.operators).map((entry, index) => {
            //   console.log(entry);
            let key = entry[0];
    
            let value = entry[1];
            console.log(value);
    
            for (let val of value) {
              console.log(value.length);
              //console.log(key, value);
              return (
                <Row className="Row">
                  {console.log(val)}
                  <ArithmeticComponent key={index} operator={val} value={val} />;
                </Row>
              );
            }
    
            console.log(key, value);
          });
        }

CodePudding user response:

     state = {
        operators: {
          topOperators: ["C", "Mod", "<"],
          numbers: ["%", ".", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
        },
      };




 renderRow() {
          return Object.values(this.state.operators).map((value) => value.map(v=>(
               <Row className="Row">
                  <ArithmeticComponent key={v} operator={v} value={v} />;
                </Row>
            ))
          );
        }

use the return statement in Array.map carefully

and should not use index be the key

  • Related