Reputation: 53
I have a var in jquery which contains values like this ..
var data = [["Local", 75], ["STD", 55], ["ISD", 96], ["VOIP", 123], ["INCOMING", 34], ["INET", 104]];
Now i have another var which contains values like ..
var data2=["LOCAL,200","STD,120","ISD,200","VOIP,500","INCOMING,234","INET,104"]
So my question is how can i convert var data2
to var data
because ,my application needs the data in the var data
format.
Please help .
Upvotes: 0
Views: 64
Reputation: 72877
This'll do it:
var data2=["LOCAL,200","STD,120","ISD,200","VOIP,500","INCOMING,234","INET,104"]
data = data2.map(function(e){return e.split(',')});
result:
data === [["LOCAL","200"], ["STD","120"], ["ISD","200"],
["VOIP","500"], ["INCOMING","234"], ["INET","104"]]
Or, if the 2nd item in the "sub-arrays" has to be a integer:
data = data2.map(function(e){
var temp = e.split(',');
temp[1] = parseInt(temp[1], 10);
return temp;
});
result:
data === [["LOCAL",200], ["STD",120], ["ISD",200],
["VOIP",500], ["INCOMING",234], ["INET",104]]
However, possibly the best solution would be to form it into a object like this:
data = data2.reduce(function(obj, current){
var temp = current.split(',');
obj[temp[0]] = parseInt(temp[1], 10)
return obj;
}, {});
result:
data === {"LOCAL":200, "STD":120, "ISD":200,
"VOIP":500, "INCOMING":234, "INET":104};
Upvotes: 5