Ask Your Question
1

How can I modify a nested value within an array in react-native?

asked 2023-06-19 19:16:55 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-19 19:22:02 +0000

qstack gravatar image

To modify a nested value within an array in React Native, you can use the spread operator and map function to create a new array with the updated value. Here's an example:

const [list, setList] = useState([
  { name: 'John', age: 25},
  { name: 'Jane', age: 30},
  { name: 'Bob', age: 35}
]);

const updateAge = (index, newAge) => {
  setList(prevList => prevList.map((person, i) =>
    i === index ? { ...person, age: newAge } : person
  ));
}

In this example, we have an array of objects called list. To update the age of a person at a specific index, we create a new array by using the map function and the spread operator. We check if the index of the current person matches the input index, and if it does, we update the age property with the new value. Otherwise, we return the original person without modifying it.

To call this function, we can pass in the index of the person we want to update and the new age value:

updateAge(1, 32); // Updates Jane's age to 32

This will update the list state with the new array that includes the updated value.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-19 19:16:55 +0000

Seen: 11 times

Last updated: Jun 19 '23