[英]Is there a way to change an item in an array of objects without changing its position?
I am modifying an array of objects. 我正在修改一个对象数组。 And I want to change a value of an item.
我想改变一个项目的值。 For that, i create a new object, the old one with some values changed.
为此,我创建了一个新对象,旧对象更改了一些值。 After that i delete the old object in the array, before concat the new one..
之后我删除数组中的旧对象,然后连接新的对象。
I have what I expected, but the item's position has changed also (the end). 我有我的预期,但项目的位置也发生了变化(结束)。
How can I change an item without changing the position? 如何在不改变位置的情况下更改项目?
let newMedoc = {};
newMedoc.quantite = newQuantite;
newMedoc.sub_total = price;
newMedoc.nom = action.value.nom;
newMedoc.prix = action.value.prix;
newMedoc.id = action.value.id;
//Delete the item in the array
nextState = {
...state,
basketOfMedicines: state.basketOfMedicines.filter(index => index !== action.value)
}
//concat a new item in the array
nextState = {
...nextState,
basketOfMedicines: [...nextState.basketOfMedicines, newMedoc]
}
return nextState || state;
If you're replacing an item, you can use map
rather than filter
: 如果您要替换项目,则可以使用
map
而不是filter
:
nextState = {...state};
nextState.basketOfMedicines = nextState.basketOfMedicines.map(entry => entry == action.value ? newMedoc : entry);
Only if the position within your application has a meaning, otherwise not. 只有当您的应用程序中的位置有意义时,否则不会。 But you have changed the currentent state within your method and you should not do that.
但是你已经改变了方法中的当前状态,你不应该这样做。 You should clone the array, eg with lodash cloneDeep or something like that.
你应该克隆数组,例如使用lodash cloneDeep或类似的东西。
Your newState.basketOfMedicine = state.basketOfMedicine.filter( ... holds just references to the objects. Have a look at the code below for clarification: 你的newState.basketOfMedicine = state.basketOfMedicine.filter(...只包含对象的引用。请看下面的代码以便澄清:
let oldState = [{a:100,b:200},{a:1000,b:2000},{a:10,b:20},{a:1,b:2},];
let arr = oldState.filter(elem => elem.a < 10); // [{a:1,b:2}]
let newState = [...arr] // destructuring
newState[0].a=50 // mutate
console.log(newState[0] === oldState[3]); // true
Here from original lodash documentation: 这里来自原始的lodash文档:
var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false
The use of lodash ist just for example, there may be other cool libraries out there. 例如,使用lodash,可能还有其他很酷的库。 Or you write a clone method by yourself.
或者你自己写一个克隆方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.