Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use reduce function in a nested state object in reactJS?

My state value is

this.state = {
    content: {
        text: {
            tag1: {
                line: "data1"
            }
            tag2: {
                line: "data2"
            }
        }
    }
}

How can I use javascript reduce() function to change the value of line of both tag1 and tag2 to "changed text"?

like image 487
Hareesh Avatar asked Jul 29 '26 16:07

Hareesh


1 Answers

Here you are:

this.setState(prevState => {
    return {
        content: {
            ...prevState.content,
            text: Object.keys(prevState.content.text).reduce((newTexts, key) => {
                return {
                    ...newTexts,
                    [key]: {
                        line: "changed text"
                    }
                }
            }, {})
        }
    }
});
like image 143
Andrii Golubenko Avatar answered Aug 01 '26 05:08

Andrii Golubenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!