update array of object without mutation
Asked Answered
F

3

9

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?

Falsework answered 5/2, 2017 at 14:25 Comment(0)
T
11

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.

Tarry answered 5/2, 2017 at 14:31 Comment(4)
can u explain why in the author doesn't have to do so? I mean do updated[0].idFalsework
the tutorial is here egghead.io/lessons/…Falsework
because in his case, arr2 will be an object, like this: const arr2 = {id:2,name:'this should be a new string'} you can try this arr2, ur code will also work :)Tarry
ah arr2 should be an object, it shouldn't be an array, I think that's my mistake, that doesn't make sense if arr2 is an array.Falsework
A
1

It's simpler and cleaner using Array.map:

const updateTodo = (list, updated) =>
    list.map((item) => {
        if (item.id !== updated.id) {
            return item;
        }

        return updated;
    });
Atropine answered 25/10, 2022 at 0:34 Comment(0)
L
0

For some reason the updated argument is an array, and therefore updated.id wont work. In that case, if you want to update the list item with that id the cleanest way to update list without mutating it would be to use Array.prototype.with() :

const updateTodo = (list, updated) => {
    const index = list.findIndex(item => item.id === updated[0].id);
    return list.with(index, updated[0]);
}
Lalise answered 6/8, 2024 at 11:46 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.