[英]Swap objects in the array without mutating the array
I am doing dragndropping and I need to swap the elements when swaping, there is an array of objects and the index of the active object and the one that is swapped, how can I swap them in js without mutating the original object我正在做拖放,交换时需要交换元素,有一个对象数组和活动对象的索引以及交换的对象,如何在不改变原始对象的情况下在 js 中交换它们
let allData = [{name:1},{name:2},{name:3}]
I need get after swapping交换后我需要得到
[{name:2},{name:1},{name:3}]
example what i need to do例如我需要做什么
case CHANGE_TAB_ORDER:
const {activeElementIndex} = action.payload;
const {swapedElementIndex} = action.payload
return {
...state,
stages: ? here i need to swap objects in array with activeElementIndex and swapedElementIndex
}
stages is array of objects阶段是对象数组
If you want to make operations in the array without mutating the original object you should make a copy first, and then you only need a temp variable to swap the items, returning the new array.如果你想在不改变原始对象的情况下在数组中进行操作,你应该先复制一份,然后你只需要一个临时变量来交换项目,返回新数组。
const array = [{name:1},{name:2},{name:3}] // Original object const arrayCopy = Object.assign({}, array) // Clone the object! function swapItems(pos1, pos2, nextArray) { const temp = nextArray[pos1]; // Temp variable nextArray[pos1] = nextArray[pos2]; // Swap the items nextArray[pos2] = temp; return nextArray; // Return the array } const swappedArray = swapItems(0,1,arrayCopy); console.log(swappedArray) // Print the array :)
without mutating you mean create a copy?没有变异你的意思是创建一个副本? Then like this.
然后像这样。
const {activeElementIndex, swapedElementIndex} = action.payload
return {
...state,
stages: (stages => {
[stages[activeElementIndex], stages[swapedElementIndex]] =
[stages[swapedElementIndex], stages[activeElementIndex]];
return stages })([...state.stages])
}
(If you want to save an old then just replace [...state.stages] in my code with state.stages) (如果你想保存一个旧的,那么只需用 state.stages 替换我代码中的 [...state.stages])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.