如何在更改键后移动数组中的对象

时间:2016-08-10 20:21:31

标签: javascript arrays sorting object

我有一个数组,其中的对象按键排序'顺序'

[
  {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'之后移动数组中的对象。在两个方向的某个对象

2 个答案:

答案 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'));