Shawn Sheehan
Shawn Sheehan

Reputation: 191

set state array with nested array values from object

I initialize component state with the store state which pulls api data. I filter the array of data by object name. This then will setState with the object chosen by the user via a button. This works, all objects change without issue. The problem I cannot for the life of me figure out is what I want is to setState onClick with a nested array of objects associated with the category. So each category object has a nested subCategory array which holds many subCategories.

So a generic example would be:

const arr = [
 { name: 'Do', id: 1, sub: [{sub_id: 1, something: 'dog'}, {sub_id: 1, something: 'cat'}] },
 { name: 'Re', id: 2, sub: [{sub_id: 2, something: 'bird'}, {sub_id: 2, something: 'mouse'}] },
 { name: 'Me', id: 3, sub: [{sub_id: 3, something: 'lion'}, {sub_id: 3, something: 'moose'}] }
];
class BrainFart extends Component {
    constructor(props) {
       super(props)
       this.state = { foo: [] }
    }
    handleArray() {
      const stuff = arr.filter(c => c.sub)
      this.setState({foo: stuff})
    }

} 

This will not set state with the nested array of sub... Any thoughts? Thank you

Upvotes: 3

Views: 2274

Answers (1)

Carloluis
Carloluis

Reputation: 4320

Update your handleArray function to:

handleArray() {
    const stuff = arr.filter(c => c.sub);

    this.setState({ foo: [...this.state.foo, ...stuff] });
}

Note the change when setting new value for foo property on component state. In this case we create a new array based on the previous and new data (stuff).

Read more on react docs about how to modify component state.


Current problem is setting foo to the output of foo.push(stuff).

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Read more about push

Upvotes: 4

Related Questions