Home > Back-end >  Updating array without changing its order
Updating array without changing its order

Time:02-20

From what I understand you should never mutate an object inside an array directly in react native, however say that I want to update a specific object inside an array - but still keep the same index nr and position of that object, selectedGoal in this case. How would I do that?

Now it keeps adding it to the end, which makes the item always appear in the end when it's manipulated.

const [goals, setGoals] = useState([])

...other code here...

    const updatedGoal = [...goals.filter(goal=>goal.id !== selectedGoal.id), selectedGoal]
    setGoals(updatedGoal)

CodePudding user response:

Filtering with state:

const updatedGoal = goals.filter(item => item.id === id);
setGoals(updatedGoal);

You can use map instead and a if ternary to return the new object or the old one instead if you want to change something inside the list:

const updatedGoal = goals.map(item => item.id === id ? {} : item);
setGoals(updatedGoal);

You can also pass the new value directly inside the state:

setGoals(prev => prev.map(item => item.id === id ? {} : item));

Filtering with same logic:

setGoals(prev => prev.filter(item => item.id === id));

EDIT

In your code case, your are filtering the the goals that not match the id and putting the selectedGoal at the end of the list:

const updatedGoal = [...goals.filter(goal=>goal.id !== selectedGoal.id), selectedGoal]

If you want to update a specific item you should try the map keyword like my example, inside the map you can match the selectedId and change the object, something like this:

const updatedGoal = goals.map(item => item.id === selectedGoal.id
? ({
   ...item, // this keep attributes you dont want to change
   done: true, // here you can change other attributes
   foo: "bar",
  })
: item);

  • Related