Reputation:
I have an array of objects stored in state using React
this.state= {
people: [
{
name: 'Tom',
hobbies: ['dancing', 'swimming']
}, {
name: 'Dean',
hobbies: ['playing', 'wondering']
}, {
name: 'Jack',
hobbies: ['shooting', 'hiking']
}, {
name: 'Natalie',
hobbies: ['rock', 'cats']
}
]
};
I want to update the state by removing one specific element from hobbies. I tried to copy people array from state, then iterate through every person object then through every hobbies array to then check if the element is the one I want to remove, but I didn't manage to remove it, state was not changing. The thing I tried was to map it and afterwards filter.
What is the easiest and fastest way to do it? I just started learning React so I want to do it with setTimeout.
At the moment I have only code to choose random hobby from random person.
setTimeout(() => {
const randInst = Math.floor(Math.random() * this.state.people.length);
const hobbyIndex = Math.floor(Math.random() * this.state.people[randInst].hobbies.length);
}, 500);
Upvotes: 3
Views: 2814
Reputation: 5012
You should create a new array and then set it as the new value for people
in the state. One of the way is to use Array.prototype.map function.
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
For example, you could do it like this:
const randomPersonIndex = Math.floor(Math.random() * this.state.people.length);
const randomHobbyIndex = Math.floor(Math.random() * this.state.people[randomPersonIndex].hobbies.length);
this.setState({
people: this.state.people.map((person, index) => {
if (randomPersonIndex !== index) {
return person; // not person we are targeting, don't change it
} else {
return {
...person,
hobbies: person.hobbies.filter((v, i) => i !== randomHobbyIndex),
}
}
});
});
I made set up a codesandbox to demonstrate this for you. Check it out here.
Upvotes: 2