String to Data Object

S

samseed

Hi, I have a delimited string that I would like to load into a data
object. Here is what I have so far:

//single string of data; each record is delimited by "%"
//and each value within each record is delimited by ";"
var myString = "foo1;001;bar1%foo2;002;bar2%foo3;003;bar3%";

//split each record into an array
var myRecords = myString.split("%");

Now that I have each record in an array, I need to load each array
element into a data object property as follows:

myData[0] = {prop1:"foo1",prop2:"001",prop3:"bar1"};
myData[1] = {prop1:"foo2",prop2:"002",prop3:"bar2"};
myData[2] = {prop1:"foo3",prop2:"003",prop3:"bar3"};

Is there a way to go from the string straight to the data object, or
should I use the above process? How can I split each array element into
3 properties for the data object? Thanks.
 
R

RobG

samseed said:
Hi, I have a delimited string that I would like to load into a data
object. Here is what I have so far:

//single string of data; each record is delimited by "%"
//and each value within each record is delimited by ";"
var myString = "foo1;001;bar1%foo2;002;bar2%foo3;003;bar3%";

The extra '%' at the end will create an empty element in myRecords when
you split myString. You should either make sure that never happens, or
modify the conversion routine to deal with it appropriately.
//split each record into an array
var myRecords = myString.split("%");

Now that I have each record in an array, I need to load each array
element into a data object property as follows:

myData[0] = {prop1:"foo1",prop2:"001",prop3:"bar1"};
myData[1] = {prop1:"foo2",prop2:"002",prop3:"bar2"};
myData[2] = {prop1:"foo3",prop2:"003",prop3:"bar3"};

Is there a way to go from the string straight to the data object, or
should I use the above process? How can I split each array element into
3 properties for the data object? Thanks.


var myString = "foo1;001;bar1%foo2;002;bar2%foo3;003;bar3";
var myRecords = myString.split("%");
var temp, myData = [];
for (var i=0, m=myRecords.length; i<m; ++i){
myData = {};
temp = myRecords.split(';');
for (var j=0, n=temp.length; j<n; ++j){
myData['prop'+j] = temp[j];
}
}

Should do the trick. If the delimiters appear anywhere in myString that
they shouldn't, myData will likely be junk.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top