1

So consider the following:

renderCharacterSheetInfo() {
    let rows = [];
    let elements = [];
    let rowCount = 0;

    if (!this.state.loading) {

      const characterSheet = {
        strength: this.state.characterSheet.base_strength,
        dexterity: this.state.characterSheet.base_dexterity,
        agility: this.state.characterSheet.base_agility,
        intelligence: this.state.characterSheet.base_intelligence,
        health: this.state.characterSheet.base_health,
        gold: this.state.characterSheet.gold,
      };

      for(const key in characterSheet) {
        if (rowCount < 3) {
          elements.push(<div className="col-md-4" key={key}>{characterSheet[key]}</div>);
          rowCount++;
        } else {
          rows.push(elements);
          rowCount = 0;
          elements = [];
          elements.push(<div className="col-md-4" key={key}>{characterSheet[key]}</div>);
        }
      }
    }

    console.log(rows);
  }

What I am attempting to do is loop through the characterSheet object and create an array, rows, of arrays: [[3 divs], [3 divs]].

Whats happening is, in the console, [[3 divs]] it loops though and creates the divs for the first three keys, but not the last three keys.

I am sure this is overly complicated, but Im not sure what to do here.

  • Expected: [[3 divs], [3 divs]]
  • Actual: [[3 divs]]

1 Answer 1

2

I am assuming you want to split the rows into 3 divs each. A simpler way would be as shown and works even if there are more than six keys in future.

Basically you divide the index by 3 to get the first index and then push the items inside the nested array at that index.

ie, for keys 0,1,2 the index would be 0 for keys 3,4,5 the index would be 1 and so on...

renderCharacterSheetInfo() {
    if (!this.state.loading) {
      const characterSheet = {
        strength: this.state.characterSheet.base_strength,
        dexterity: this.state.characterSheet.base_dexterity,
        agility: this.state.characterSheet.base_agility,
        intelligence: this.state.characterSheet.base_intelligence,
        health: this.state.characterSheet.base_health,
        gold: this.state.characterSheet.gold,
      };

      let rows = Object.keys(characterSheet).reduce((_rows,key,index) => {
        let rowIndex = Math.floor(index/3);
        if(!_rows[rowIndex]) {
            _rows[rowIndex] = []; //initialize with empty to push
        }

        _rows[rowIndex].push(<div className="col-md-4" key={key}>
 {characterSheet[key]} </div>)
        return _rows;
      },[]);

    console.log(rows);
  }
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.