我有一个数组,其中的对象按键排序'顺序'
[
{order: 1, id: 1, title: elem1},
{order: 2, id: 2, title: elem2},
{order: 3, id: 3, title: elem3},
{order: 4, id: 4, title: elem4},
{order: 5, id: 5, title: elem5}
]
更改密钥' order'在' elem2'到' 4',数组应该看起来像这样
[
{order: 1, id: 1, title: elem1},
{order: 2, id: 3, title: elem3},
{order: 3, id: 4, title: elem4},
{order: 4, id: 2, title: elem2},
{order: 5, id: 5, title: elem5}
]
我想在更改键' order'之后移动数组中的对象。在两个方向的某个对象
答案 0 :(得分:2)
您可以使用Array.prototype.sort()功能:
var elem1, elem2, elem3, elem4, elem5;
var arr = [
{order: 1, id: 1, title: elem1},
{order: 2, id: 2, title: elem2},
{order: 3, id: 3, title: elem3},
{order: 4, id: 4, title: elem4},
{order: 5, id: 5, title: elem5}
];
arr[1].order = 4;
arr[3].order = 2;
arr.sort((a, b) => a.order > b.order);
答案 1 :(得分:1)
您可以使用.splice()
移动项目,.forEach()
更新order
属性。
var arr = [
{order: 1, id: 1, title: 'elem1'},
{order: 2, id: 2, title: 'elem2'},
{order: 3, id: 3, title: 'elem3'},
{order: 4, id: 4, title: 'elem4'},
{order: 5, id: 5, title: 'elem5'}
];
function moveItem(arr, from, to) {
arr.splice(to - 1, 0, arr.splice(from - 1, 1)[0]);
arr.forEach(function(e, i) { e.order = i + 1; });
}
moveItem(arr, 2, 4);
// formatted output
console.log(JSON.stringify(arr).split('},').join('},\n'));