我有一个像这样的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"
}
]
我需要的是将type
和Value
数据放入二维数组中。我的最终结果应该是这样的;
var data = [
[
"Rainfall",
158
],
[
"Temparature",
31.1
],
[
"Wind",
4
],
[
"Humidity",
69
]
]
请注意我从后端服务获得myArr
结果,并且此数组的长度可以动态更改。我怎样才能做到这一点。谢谢
答案 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>