I have 3 variables with strings containing comma separated values (I don't know how many) which I want to combine into jQuery objects.
"name1,name2,name3,nameN"
"value1,value2,value3,valueN"
"id1,id2,id3,idN"
to:
var item1 = { name: name1, value: value1, id: id1 };
var item2 = { name: name2, value: value2, id: id2 };
var item3 = { name: name3, value: value3, id: id3 };
var itemN = { name: nameN, value: valueN, id: idN };
To then iterate an operation over each item, for example to append a list:
<h3>items</h3>
<ul>
<li>item1</li>
<ul>
<li>value: <b>value1</b></li>
<li>id: <b>id1</b></li>
</ul>
[...]
<li>itemN</li>
<ul>
<li>value: <b>valueN</b></li>
<li>id: <b>idN</b></li>
</ul>
<ul>
What is the best way to do this?
Split the String into an array of Strings using the split() method. Now, convert the obtained String array to list using the asList() method of the Arrays class.
Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .
Use the str. split() method to convert a comma-separated string to a list, e.g. my_list = my_str. split(',') .
You can build an array of your items like this:
var names = "name1,name2,name3,nameN";
var values = "value1,value2,value3,valueN";
var ids = "id1,id2,id3,idN";
var namesArray = names.split(",");
var valuesArray = values.split(",");
var idsArray = ids.split(",");
var item, items = [];
for (var i = 0; i < namesArray.length; i++) {
item = {};
item.name = namesArray[i];
item.value = valuesArray[i];
item.id = idsArray[i];
items.push(item);
}
Then, to build the HTML from that, you can do this:
var main = $("<ul>");
var str = "";
for (var i = 0; i < items.length; i++) {
str += "<li>" + items[i].name + "</li><ul><li>value: <b>" + items[i].value + "</b></li>";
str += "<li>id: <b>" + items[i].id + "</b></li></ul>";
}
main.html(str);
$(document.body).append("<h3>items</h3>")
$(document.body).append(main);
You can see it work here: http://jsfiddle.net/jfriend00/yWU3L/4/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With