想想我有一个对象数组如下:
var array = [
{ name: "A", position: "0" },
{ name: "B", position: "1" },
{ name: "C", position: "2" },
{ name: "D", position: "3" },
{ name: "E", position: "4" },
{ name: "F", position: "5" }
];
假设用户拖动了位置为4的元素并将其放在位置为1的元素上。
var replacedItem = { name: "E", position: "4" };
var destinationItem = { name: "B", position: "1" };
如何使用javascript重新排列元素的位置,使数组包含以下值:
var array = [
{ name: "A", position: "0" },
{ name: "E", position: "1" },
{ name: "B", position: "2" },
{ name: "C", position: "3" },
{ name: "D", position: "4" },
{ name: "F", position: "5" }
];
谢谢,
答案 0 :(得分:1)
您可以使用splice
分两步移动元素:
var a = [ ... ];
var temp = a.splice(4, 1); // remove element at index 4
a.splice(1, 0, temp[0]); // insert the removed element at index 1
splice()
返回已删除元素的数组(在本例中为1元素数组),这就是您需要下标temp
的原因。
由于你只想移动name
属性,一种方法是将数组分成两个数组,重新排列对应name
属性的数组并重新组合:
var fromIndex = 4, toIndex = 1;
// Step 1: collect names and positions in separate arrays
var names = [], positions = [];
array.forEach(function(elt) {
this.names.push(elt.name);
this.positions.push(elt.position);
}, {names: names, positions: positions});
// Step 2: do a circular permutation of the names between the indexes (inclusive)
var temp = names.splice(fromIndex, 1);
names.splice(toIndex, 0, temp[0]);
// Step 3: recombine names and positions into an array of objects
var n = array.length;
array.length = 0;
for (var i = 0; i < n; ++i) {
array.push({name: names[i], position: positions[i]});
}
答案 1 :(得分:1)
1 - destionNationItemIndex
4 - replacementItemIndex
你可以试试这个: -
var removed = array.splice(4, 1);
array.splice(1, 0, removed[0]);
for (var i = 1; i <= 4; i++) {
array[i].position = (parseInt(array[i - 1].position) + 1).toString();
}
打印您需要的内容: -
var array = [
{ name: "A", position: "0" },
{ name: "E", position: "1" },
{ name: "B", position: "2" },
{ name: "C", position: "3" },
{ name: "D", position: "4" },
{ name: "F", position: "5" }
]
答案 2 :(得分:-2)
这是实现这一目标的最简单的逻辑:
var array = [
{ name: "A", position: "0" },
{ name: "B", position: "1" },
{ name: "C", position: "2" },
{ name: "D", position: "3" },
{ name: "E", position: "4" },
{ name: "F", position: "5" }
];
var replacedItem = { name: "E", position: "4" };
var destinationItem = { name: "B", position: "1" };
for(var i=0; i<array.length; i++){
if(array[i].position == replacedItem.position)
array[i].position = destinationItem.position;
else if(array[i].position == destinationItem.position)
array[i].position = replacedItem.position;
}
新阵列将是:
var array = [
{ name: "A", position: "0" },
{ name: "B", position: "4" },
{ name: "C", position: "2" },
{ name: "D", position: "3" },
{ name: "E", position: "1" },
{ name: "F", position: "5" }
];
你只需交换他们的位置。
<强> DEMO 强>