在不改变阵列的情况下交换阵列中的对象



我正在进行drandropping,在交换时我需要交换元素,有一个对象数组和活动对象的索引以及被交换的对象,我如何在js中交换它们而不改变原始对象

let allData = [{name:1},{name:2},{name:3}]

我需要得到后交换

[{name:2},{name:1},{name:3}]

示例我需要做什么

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是对象阵列

如果你想在不改变原始对象的情况下在数组中进行操作,你应该先做一个副本,然后你只需要一个临时变量来交换项,返回新的数组。

const array = [{name: 1}, {name: 2}, {name: 3}]; // Originalarray
const arrayCopy = array.slice(); // Clone the array
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 :)

如果不进行更改,您的意思是创建一个副本?那就这样吧。

const {activeElementIndex, swapedElementIndex} = action.payload
return {
...state,
stages: (stages => { 
[stages[activeElementIndex], stages[swapedElementIndex]] =
[stages[swapedElementIndex], stages[activeElementIndex]];
return stages })([...state.stages])  
}

(如果你想保存一个旧的,那么只需将我的代码中的[…state.stages]替换为state.stages(

最新更新