如何使用JavaScript或Jquery向上或向下移动数组项?

时间:2014-03-28 13:15:13

标签: javascript jquery json

我有以下json

{  "EmployeeLists": [
{
  "ID": 1,
  "NAME": "Anand",
  "Salary": 90000
},
{
  "ID": 2,
  "NAME": "Anbu",
  "Salary": 80000 
},
{
  "ID": 3,
  "NAME": "Bala",
  "Salary": 85000
}  ]}

我想将数组项2向上或向下移动。预期的产出如下。

{  "EmployeeLists": [
{
  "ID": 2,
  "NAME": "Anbu",
  "Salary": 80000
},
{
  "ID": 1,
  "NAME": "Anand",
  "Salary": 90000
},
{
  "ID": 3,
  "NAME": "Bala",
  "Salary": 85000
} ]}

1 个答案:

答案 0 :(得分:4)

您可以像这样交换2个元素:

var x = EmployeeLists[2];
EmployeeLists[2] = EmployeeLists[1];
EmployeeLists[1] = x;