如何将JSON对象的第一个元素移动到最后?

时间:2017-04-04 00:50:52

标签: javascript jquery json

嗨,我有这样的JSON:

[
  "supplier" : "Apple",
  "features" : {
      "0": [
        {
          "feature_id": "58d1b42ec2ef165bbfca0873",
          "symbol": "tick"
        },
        {
          "feature_id": "58d4b843bd966f52093ce32f",
          "symbol": "cross"
        }
      ],
      "1":[
        {
          "feature_id": "58d1b42ec2ef165bb33422087",
          "symbol": "tick"
        },
        {
          "feature_id": "58d4b843bd91ads2jfloice32",
          "symbol": "cross"
        }

      ]
  },
  "supplier" : "Orange",
  "features" : {
      "0": [
        {
          "feature_id": "58d1b42ec2ef165bbfca0873",
          "symbol": "tick"
        },
        {
          "feature_id": "58d4b843bd966f52093ce32f",
          "symbol": "cross"
        }
      ],
      "1":[
        {
          "feature_id": "58d1b42ec2ef165bb33422087",
          "symbol": "tick"
        },
        {
          "feature_id": "58d4b843bd91ads2jfloice32",
          "symbol": "cross"
        }

      ]
  }
]

如何使用jQuery / javascript将功能对象键'0'移动到键'0'后的末尾?我试过使用array.push(array.shift());但它抛出错误说“array.shift()”不是一个函数。我猜.features不是数组,所以如何将对象移动到最后?

2 个答案:

答案 0 :(得分:0)

是否存在功能是对象而不是数组的原因? 你可以这样做:

_top
如果您只是计划使用数字作为键,那么

没有问题。否则,您可以使用"features" : [ [ { "feature_id": "58d1b42ec2ef165bbfca0873", "symbol": "tick" }, { "feature_id": "58d4b843bd966f52093ce32f", "symbol": "cross" } ], [ { "feature_id": "58d1b42ec2ef165bb33422087", "symbol": "tick" }, { "feature_id": "58d4b843bd91ads2jfloice32", "symbol": "cross" } ] } 获取对象键的数组(在您的情况下为“1”,“2”,...),并在需要时使用这些键引用该对象。

答案 1 :(得分:0)

使用临时变量交换

var data = {

  "supplier" : "Apple",
  "features" : {
      "0": [
        {
          "feature_id": "58d1b42ec2ef165bbfca0873",
          "symbol": "tick"
        },
        {
          "feature_id": "58d4b843bd966f52093ce32f",
          "symbol": "cross"
        }
      ],
      "1":[
        {
          "feature_id": "58d1b42ec2ef165bb33422087",
          "symbol": "tick"
        },
        {
          "feature_id": "58d4b843bd91ads2jfloice32",
          "symbol": "cross"
        }

      ]
  }
  };


function swap(obj,index1,index2){
    var temp = obj[index1];
    obj[index1] = obj[index2];
    obj[index2] = temp;
    return obj;
}

data.features = swap(data.features,"0","1");

// now features [“0”]< ==>特征[ “1”];