简体   繁体   English

使用javascript es6更新对象数组

[英]update array of object using javascript es6

is there any other way to write update an item in array of object other than below code? 除了下面的代码,还有其他任何方法可以写更新对象数组中的项吗?

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

Wait, is above function even working? 等一下,上面的功能还可以吗? https://jsbin.com/sifihocija/2/edit?js,console https://jsbin.com/sifihocija/2/edit?js,控制台

The way you are doing it, is the right way to do it. 您执行的方式是正确的方式。 However it is not working for you because in your case updated is an array and not an object and hence you only need to access the id of the first element of the array 但是它对您不起作用,因为在您的情况下, updated是一个数组而不是一个对象,因此您只需要访问该数组的第一个元素的id

const updateTodo = (list, updated) => {

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

   return [
   ...list.slice(0,index),
   updated[0],
   ...list.slice(index+1)
   ]
}

JSBIN 吉宾

However I prefer the library immutability-helper to perform any updates on the data you can do that like 但是我更喜欢使用库immutability-helper对您可以执行的数据进行任何更新

import update from 'immutability-helper';
const updateTodo = (list, updated) => {
const index = list.findIndex(item => return item.id === updated[0].id)
   return update(list, {
        [index]: {
              $set: updated[0];
        }

   })
}

One advantage of using immutabilty-helper is that its gives more control when the data is highly nested 使用immutabilty-helper程序的一个优点是,当高度嵌套数据时,它可以提供更多控制

The simplest way to update(addition/deletion) an array is to use splice method. 更新(添加/删除)数组的最简单方法是使用拼接方法。

it takes the first argument as the index, second as the no of elements you want to remove and next arguments for the addition. 它以第一个参数为索引,第二个为要删除的元素号,以及下一个要添加的参数。

You are doing to much. 您正在做很多事情。 No need to manipulate the array if you know the index. 如果您知道索引,则无需操纵数组。

const items = [{id: 1, value: 1}, {id: 2, value: 2}, {id: 3, value: 3}];
items[2] = {id: 4, value: 4};
console.log(items); //last element changed

if you care about no side effects copy the array before 如果您没有副作用,请在复制数组之前

const items = [{id: 1, value: 1}, {id: 2, value: 2}, {id: 3, value: 3}];
const copy = items.slice();
copy[2] = {id: 4, value: 4};
return copy;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM