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
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)] );
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)]
});
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.
let data = [];
myArr.map( a => {
data.push([a.type, a.Value]);
});
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.