Reputation: 41455
i have a javascript array like this
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"
}
]
what i need is to put type
and Value
data into 2 dimension array. my end result should be like this;
var data = [
[
"Rainfall",
158
],
[
"Temparature",
31.1
],
[
"Wind",
4
],
[
"Humidity",
69
]
]
note that myArr
results i'm getting from the backend service and the length of this array can be change dynamically. how can i do this. thanks
Upvotes: 0
Views: 115
Reputation: 15725
You can simply use Array.map
function to map object array to two dimensional array.
var data = myArr.map(function(o){
return [o.type, o.Value]
});
Also if you want value to be converted into a float
number instead of string
, do this with pasreFloat
var data = myArr.map(function(o){
return [o.type, pasreFloat(o.Value)]
});
Upvotes: 5
Reputation: 1137
I am familiar with underscore.js: you may use:
_.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>
Upvotes: -1
Reputation: 68685
Try this:
With foreach
function
Documentation: Array.forEach
var data = [];
myArr.forEach(x => data.push([x.type, parseFloat(x.Value)]))
With map
function
Documentation: Array.Map
var data = myArr.map(x => [x.type, parseFloat(x.Value)] );
Upvotes: 5
Reputation: 852
let data = [];
myArr.map( a => {
data.push([a.type, a.Value]);
});
Upvotes: 1
Reputation: 11620
You can use Arrays.map function to get the result:
var data = myArr.map(function(input){ return [input.type, input.Value]; });
This function will transform each element of your array into another element, because you need an array of arrays, your mapping function must create an array out of an object.
Upvotes: 2