最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - update array of object without mutation - Stack Overflow

programmeradmin6浏览0评论

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

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)
   ]
}

,console but failed to produce the result that the author did, what's wrong?

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

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./sifihocija/2/edit?js,console but failed to produce the result that the author did, what's wrong?

Share Improve this question asked Feb 5, 2017 at 14:25 Zea LithZea Lith 4211 gold badge7 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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./pazakujava/edit?js,console

Let me know if you need any help in this.

It's simpler and cleaner using Array.map:

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

        return updated;
    });

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]);
}
发布评论

评论列表(0)

  1. 暂无评论