用Angularjs或Jquery重构Json

时间:2012-12-04 05:56:21

标签: javascript jquery

使用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
      }
   ]
}

1 个答案:

答案 0 :(得分: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]);
}

Here's a fiddle (using Angular) demonstrating before and after output