Home > Enterprise >  Looping over Object with key being a string and value being an array of 2 numbers
Looping over Object with key being a string and value being an array of 2 numbers

Time:01-27

I'm new to React and am having difficulty with looping and displaying the result. I'm trying to figure out how to loop over an object with the key being a string and the value being an array of numbers that I need to divide. For example here is the data enter image description here

I want to print something like "you've scored 0/40 Customer points" and the same for the rest of them.

Here is my code

    getGaugeData = () => {
    const ranges = gaugeStore.getRanges();
    console.log(ranges);
    // const gaugeScore = Object.entries(ranges).forEach(([key, value]) => <div>`you've earned ${value[0]}/${value[1]} ${key} points!`</div>);
    // console.log('score', gaugeScore);
}

Here is where the function getGaugeData is invoked:

    render() {
    const scale = courseDataStore.getCustomData(`mti-${this.props.saveKey}`);
    return (
        <div className={`${this.classNamePrefix}-view ${this.props.breakpoint}`} style={{ backgroundImage: `url(${this.props.backgroundImage})` }}>
            <NestedComponent component={this.props.gauges} parent={this} shouldIgnoreEmpty={false} />
            <div className={`${this.classNamePrefix}-content`}>
                <h2 className={`${this.classNamePrefix}-heading`} dangerouslySetInnerHTML={{ __html: this.props.heading}} />
                <div className={`${this.classNamePrefix}-body`} dangerouslySetInnerHTML={{ __html: this.props.body}} />
                {this.getGaugeData()}
                {this.props.continueBtn && this.props.continueBtn.data && this.props.continueBtn.data.label &&
                    <NestedComponent component={this.props.continueBtn} parent={this} onClick={this.props.navigateNext} />
                }
            </div>
        *{this.getGaugeData()}*
        </div>
    );
}

But when I log the gaugeScore variable to the console I get undefined instead of the div printing 4 times.

CodePudding user response:

The easiest way or looping thorugh all object entries is to call Object.entries and then loop through the array.

The problem you have is that you need to use map instead of forEach, because you want to map a list of data into a list of jsx elements.

const gaugeScore = Object.entries(ranges).map(([key, value]) => <div key={key}>`you've earned ${value[0]}/${value[1]} ${key} points!`</div>)

Something like this should work. And remember you can put this code in the jsx netween brackets without assigning it to a variable.

  •  Tags:  
  • Related