By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,473 Members | 3,504 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,473 IT Pros & Developers. It's quick & easy.

String to Data Object

P: n/a
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.

Nov 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
samseed wrote:
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[i] = {};
temp = myRecords[i].split(';');
for (var j=0, n=temp.length; j<n; ++j){
myData[i]['prop'+j] = temp[j];
}
}

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

--
Rob
Nov 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.