1

用 Angularjs 或 Jquery 重构 Json 的最佳方法是什么?

我得到一个具有以下格式的 json

    [
  {
     "address":"balh",
     "lat":123,
     "long":456
  },
  {
     "address":"balh",
     "lat":321,
     "long":543
  },
  {
     "address":"balh",
     "lat":432,
     "long":333
  },
  {
     "address":"balh",
     "lat":123,
     "long":456
  },
  {
     "address":"balh",
     "lat":321,
     "long":543
  },
  {
     "address":"balh",
     "lat":432,
     "long":333
  }
]

我需要的格式是将它与以下三个分组..

    {
   "1":[
      {
         "address":"balh",
         "lat":123,
         "long":456
      },
      {
         "address":"balh",
         "lat":321,
         "long":543
      },
      {
         "address":"balh",
         "lat":432,
         "long":333
      }
   ],
   "2":[
      {
         "address":"balh",
         "lat":123,
         "long":456
      },
      {
         "address":"balh",
         "lat":321,
         "long":543
      },
      {
         "address":"balh",
         "lat":432,
         "long":333
      }
   ]
}
4

1 回答 1

2

这对我来说更像是一个直接的 JavaScript 问题。

下面的代码应该将您的数组分解为一个数组字典,每个数组包含三个(或更少)对象:

var yourArray = [/*whatever it is in here*/];

var output = {};

for(var i = 0, c = 1, current = null; i < yourArray.length; i++) {
    if(i % 3 == 0) {
        output[c++] = current = [];
    }
    current.push(yourArray[i]);
}

这是一个小提琴(使用Angular)在输出之前和之后演示

于 2012-12-04T06:06:05.820 回答