Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing and Pulling an nested array with setState with Javascript

Im doing an application where I have one state with some results of athletes.

This is how my data is organized:

const startData = [
  { name: "Medina", results: [5, 5, 17, 17, 5, 1, 2, 1, 9, 9] },
  { name: "Filipe", results: [9, 2, 5, 17, 1, 3, 9, 2, 17, 1] },
  { name: "Jordy", results: [3, 3, 17, 5, 2, 9, 3, 5, 9, 1] },
  { name: "Italo", results: [1, 5, 17, 5, 17, 2, 17, 9, 2, 1] },
  { name: "Kolohe", results: [2, 17, 5, 2, 3, 3, 17, 17, 5, 1] },
  { name: "Kanoa", results: [9, 9, 1, 9, 5, 5, 17, 9, 17, 1] }
  //"Italo": []
];

Now, I want to add some positions on this results array inside the state. For instance:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { data: startData };
  }

handleChange = surfer => event => {
    this.setState("HOW TO ADD THIS EVENT VALUE INSIDE A SURFER RESULTS")
};

So, for instance, for the surfer with name "Medina" I want to add an element inside this results array (the value of the event.target.value)

How can I do this?

like image 598
Fernando Maymone Avatar asked May 13 '26 05:05

Fernando Maymone


1 Answers

You can access and modify your state like this

handleChange = surfer => event => {
    this.setState(prev => ({
        data : prev.data.map(item =>{
            if(item.name === surfer.name)
                return {...item, results: item.results.concat(event.target.value)}

            return item
        })
    }))
};

map over your data checking if surfer is the selected one, case true spread the original object, and concat to it's results the e.target.value. Case false just return the item.

To remove an element use filter

handleChange = surfer => event => {
    this.setState(prev => ({
        data : prev.data.map(item =>{
            if(item.name === surfer.name)
                return {...item, results: item.results.filter(i => 1 === 1)}

            return item
        })
    }))
};
like image 82
Dupocas Avatar answered May 15 '26 20:05

Dupocas



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!