Reputation: 2909
I am having confusion on how to do it with $.map function instead of regular $.each
.
I have json data like this.
var arr = {
"x1" :[11,22,33],
"y1":[44,55,66],
"y2":[77,88,99]
};
And result should be array = [[x1,y1,y2], ...]
var result = [[11,44,77],[22,55,88],[33,66,99]];
And I want function to be dynamic , it should not depend on arr.x1 etc .For example If i give it array like
var arr2 = {
"aaa" :[11,22,33],
"sss":[44,55,66],
"dd":[77,88,99],
"dddd":[77,88,99],
};
It should add up all array like above dynamically as it have now 4 sub arrays so result should be three sub-arrays of four elements each.
I should be able to do it with $.each
etc but purpose is to learn $.map.
UPDATE: My guess is pure $.map solution will be something like nested maps:
_elements = $.map(_elements, function(e) {
return [$.map(e,function(v) {
return v;
})];
});
Upvotes: 1
Views: 6606
Reputation: 382102
You can build your array like this :
var arr = {
"x1" :[11,22,33],
"y1":[44,55,66],
"y2":[77,88,99]
};
var keys = Object.keys(arr), result = [], l=arr[keys[0]].length;
for(var i=0; i<l; i++) result.push($.map(keys, function(k){ return arr[k][i] }));
This builds exactly the array you're asking for.
Upvotes: 3