Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update array of object without mutation

I'm following a react tutorial but I'm lost. I don't understand starting line 9.

enter image description here

so I tried to make a little miarature

const updateTodo = (list, updated) => {
   const index = list.findIndex(item => item.id === updated.id)
   return [
   ...list.slice(0,index),
   updated,
   ...list.slice(index+1)
   ]
}

https://jsbin.com/sifihocija/2/edit?js,console but failed to produce the result that the author did, what's wrong?

like image 530
Zea Lith Avatar asked Feb 05 '17 14:02

Zea Lith


People also ask

How do you update an object without mutating?

Add or replace an element to an object Similar to adding elements to arrays without mutating them, You can use the spread operator to copy the existing object into a new one, with an additional value. If a value already exists at the specified key, it will be overwritten.

How do you splice an array without mutating the original array?

Steps : Create the clone of the array using the spread operator or slice method. apply the splice method on the cloned array and return the extracted array.

How do you update an object array of values?

To update an object's property in an array of objects, use the map() method to iterate over the array. On each iteration, check if the current object is the one to be updated. If it is, modify the object and return the result, otherwise return the object as is. Copied!

How do I remove a property from an object without mutating?

A better way to delete a property without mutating is by using spread operator. const {worth, … newPerson} = person; console.


1 Answers

Issue is in this line:

const index = list.findIndex(item => item.id === updated.id)

updated is an array, to access the id, you need to specify the index also, for other array you are using loop, so item will be the each object of the array, and item.id will give you the id of each object, try this:

const index = list.findIndex(item => item.id === updated[0].id)

const arr = [
  {id:1,name:'hello'},
  {id:2,name:'hai'}
]

const arr2 = [
  {id:2,name:'this should be a new string'}
]

const updateTodo = (list, updated) => {
   const index = list.findIndex(item => item.id === updated[0].id);
   return [
   ...list.slice(0,index),
   ...updated,
   ...list.slice(index+1)
   ]
}

console.log(JSON.stringify(updateTodo(arr,arr2)))

Check the working code: https://jsbin.com/pazakujava/edit?js,console

Let me know if you need any help in this.

like image 94
Mayank Shukla Avatar answered Sep 30 '22 14:09

Mayank Shukla