改变JS数组的结构

时间:2014-11-25 16:57:59

标签: javascript arrays json

我是javascript的初学者,我有一个小问题。

我有这个:

[
  {
    "date": "2014-04-23 00:00:00",
    "volumetrie": "22458"
  },
  {
    "date": "2014-05-02 00:00:00",
    "volumetrie": "30585"
  },
  {
    "date": "2014-03-27 00:00:00",
    "volumetrie": "49536"
  }
]

我想这样:

[
  {
    "x": "2014-04-23T22:00:00.000Z",
    "y": 22458
  },
  {
    "x": "2014-05-02T22:00:00.000Z",
    "y": 30585
  },
  {
    "x": "2014-03-27T22:00:00.000Z",
    "y": 49536
  }
]

你有什么想法吗? 非常感谢您将来的答案;)

3 个答案:

答案 0 :(得分:4)

你可以通过

来完成
var origArr = [{"date": "2014-04-23 00:00:00","volumetrie": "22458"},{"date": "2014-05-02 00:00:00","volumetrie": "30585"},{"date": "2014-03-27 00:00:00","volumetrie": "49536"}];

forEach循环遍历数组的元素并创建自己的

var modifArr = [];

origArr.forEach(function(elem){
    modifArr.push({ x : (new Date(elem.date)).toISOString(), y : elem.volumetrie })
});

console.log(modifArr); // the array that you need

map

var modifArr = origArr.map(function(elem){
    return { x : (new Date(elem.date)).toISOString(), y : elem.volumetrie }
});

console.log( modifArr );

或jQuery的each

var modifArr = [];

$(origArr).each(function(index, elem){
    modifArr.push({ x : (new Date(elem.date)).toISOString(), y : elem.volumetrie })
});

console.log( modifArr );

答案 1 :(得分:4)

使用Array.map

var arr = [
  {
    "date": "2014-04-23 00:00:00",
    "volumetrie": "22458"
  },
  {
    "date": "2014-05-02 00:00:00",
    "volumetrie": "30585"
  },
  {
    "date": "2014-03-27 00:00:00",
    "volumetrie": "49536"
  }
];

var newArr = arr.map(function(item){
   return {x: item.date, y: item.volumetrie};
});

答案 2 :(得分:0)

使用map()。例如:

var test = [
    {
        "date": "2014-04-23 00:00:00",
        "volumetrie": "22458"
    },
    {
        "date": "2014-05-02 00:00:00",
        "volumetrie": "30585"
    },
    {
        "date": "2014-03-27 00:00:00",
        "volumetrie": "49536"
    }
];
var newArr = test.map(function(key){
    return {x: key.date, y: key.volumetrie};
});
console.log(newArr);