javascript数组到二维数组

时间:2016-08-01 06:13:14

标签: javascript arrays

我有一个像这样的javascript数组

var myArr = [  

   {  
      "Year":"2015",
      "Month":"January",
      "Value":"15.8",
      "District":"Anuradhapura",
      "type":"Rainfall"
   },
   {  
      "Year":"2015",
      "Month":"January",
      "Value":"31.1",
      "District":"Anuradhapura",
      "type":"Temparature"
   },
   {  
      "Year":"2015",
      "Month":"January",
      "Value":"4",
      "District":"Anuradhapura",
      "type":"Wind"
   },
   {  
      "Year":"2015",
      "Month":"January",
      "Value":"69",
      "District":"Anuradhapura",
      "type":"Humidity"
   }
]

我需要的是将typeValue数据放入二维数组中。我的最终结果应该是这样的;

 var data = [  
       [  
          "Rainfall",
          158
       ],
       [  
          "Temparature",
          31.1
       ],
       [  
          "Wind",
          4
       ],
       [  
          "Humidity",
          69
       ]
    ]

请注意我从后端服务获得myArr结果,并且此数组的长度可以动态更改。我怎样才能做到这一点。谢谢

5 个答案:

答案 0 :(得分:5)

试试这个:

使用foreach功能

文档: Array.forEach

var data = [];

myArr.forEach(x => data.push([x.type, parseFloat(x.Value)]))

使用map功能

文档: Array.Map

var data = myArr.map(x => [x.type, parseFloat(x.Value)] );

答案 1 :(得分:5)

您只需使用Array.map函数将对象数组映射到二维数组。

  var data = myArr.map(function(o){
       return [o.type, o.Value]
    });

此外,如果您希望将值转换为float号而不是string,请使用pasreFloat

执行此操作
  var data = myArr.map(function(o){
       return [o.type, pasreFloat(o.Value)]
    });

答案 2 :(得分:2)

您可以使用Arrays.map函数获取结果:

     var data = myArr.map(function(input){ return [input.type, input.Value]; });

这个函数会将数组的每个元素转换为另一个元素,因为你需要一个数组数组,你的映射函数必须用一个对象创建一个数组。

答案 3 :(得分:1)

let data = [];
myArr.map( a => {

 data.push([a.type, a.Value]);

});

答案 4 :(得分:-1)

我熟悉underscore.js:您可以使用:

_.zip(_.pluck(myArr, "type"), _.pluck(myArr, "Value"));

var myArr = [  

   {  
      "Year":"2015",
      "Month":"January",
      "Value":"15.8",
      "District":"Anuradhapura",
      "type":"Rainfall"
   },
   {  
      "Year":"2015",
      "Month":"January",
      "Value":"31.1",
      "District":"Anuradhapura",
      "type":"Temparature"
   },
   {  
      "Year":"2015",
      "Month":"January",
      "Value":"4",
      "District":"Anuradhapura",
      "type":"Wind"
   },
   {  
      "Year":"2015",
      "Month":"January",
      "Value":"69",
      "District":"Anuradhapura",
      "type":"Humidity"
   }
];


alert(JSON.stringify(_.zip(_.pluck(myArr, "type"), _.pluck(myArr, "Value"))));
<script src="http://underscorejs.org/underscore-min.js"></script>