【问题标题】:Angularjs $scope array object rearrangeAngularjs $scope 数组对象重新排列
【发布时间】:2019-07-08 06:22:40
【问题描述】:

我有一个 json 数组,我将它分配给一个 $scope 对象以在前端显示。我想根据给定的 id 重新排列这个数组。 这就是我的初始数组的样子。

$scope.listData = [{
id: 1,
name: adam,
title: testing title,
description: testing description
},
{
id: 2,
name: zampa,
title: testing title,
description: testing description
},
{
id: 3,
name: Aaron,
title: testing title,
description: testing description
}]

对于重排,例如如果给定的id是3,记录的重排应该是3,1,2。

我尝试过使用 angular.forEach 循环,但没有成功。

【问题讨论】:

  • 所以您只想将具有给定 ID 的项目移动到数组的开头?
  • 正确。只是重新排列,不删除不删除。

标签: json angularjs


【解决方案1】:

这是使用splice()unshift() 的解决方案:

function moveToFront(id, array) {
  const i = array.findIndex(v => v.id === id);

  array.unshift(...array.splice(i, 1));
}

完成sn-p:

const listData = [{
    id: 1,
    name: 'adam',
    title: 'testing title',
    description: 'testing description'
  },
  {
    id: 2,
    name: 'zampa',
    title: 'testing title',
    description: 'testing description'
  },
  {
    id: 3,
    name: 'Aaron',
    title: 'testing title',
    description: 'testing description'
  }
];

function moveToFront(id, array) {
  const i = array.findIndex(v => v.id === id);
  
  array.unshift(...array.splice(i, 1));
}

moveToFront(3, listData);

console.log(listData);

【讨论】:

  • unshift 函数只返回一个数字,而不是数组。
  • @ShaurBinTalib 该函数就地修改数组(根据问题的要求)。无需退货。
  • 是的,我明白了。它按照我的要求完美地工作。谢谢你
【解决方案2】:

//假设最初是按id排序的,从第一个开始

listData.splice(0, 0, listData.splice(id - 1, 1)[0]);

【讨论】:

  • 返回空数组
  • listData 本身已更改
  • 这只会工作一次。第二次ID的顺序会有所不同。
  • 是的,这就是问题所在。然而,我得到了我的答案。谢谢你的帮助。
  • 是的,但是,不删除只重新排列的想法是不对的,总是有新的数组副本,无论如何问题都解决了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多