我有这样的数据结构:
[{
id: 'a',
order: 9
}, {
id: 'b',
order: 6
}, {
id: 'c',
order: 4
}, {
id: 'd',
order: 2
}]
我想以这种方式更新订单值:
[{
id: 'a',
order: 9
}, {
id: 'd',
order: 6
}, {
id: 'b',
order: 4
}, {
id: 'c',
order: 2
}]
这是一个视觉表示(按“顺序”值递减顺序):
A/B/C/D -> A/D/B/C
我正在努力用 JavaScript 编写一个函数来执行此操作,并将其作为输入:
在上面的示例中,参数为 ('d', 1)
我尝试了各种方法但没有成功,感谢任何帮助
您可以查找给定
id
所在位置的索引,确定移动订单值的方向,然后开始旋转这些:
function moveItem(data, toId, fromIndex) {
// Check validity of fromIndex, and whether there is something to do
if (!data[fromIndex] || data[fromIndex].id === toId) return;
let toIndex = data.findIndex(({id}) => id === toId);
// Check validity of the given id
if (toIndex < 0) return;
// Determine which direction to rotate by
let step = fromIndex > toIndex ? -1 : 1;
// Save the order value that will move
let {order} = data[fromIndex];
// Rotate the order values that sit on the way to the target
for (let i = fromIndex; i != toIndex; i += step) {
data[i].order = data[i + step].order;
}
// Finally set the target order
data[toIndex].order = order;
}
// Your example:
const data = [{id: 'a', order: 9 }, {id: 'b', order: 6 }, {id: 'c', order: 4 }, {id: 'd', order: 2 }];
moveItem(data, "d", 1);
console.log(data);