Reputation: 268
Hi i have a set of words that's retrieved by php and displayed on two hidden text field like this:
The titles:
Red Apple, Grapes, Green Apple, Orange
The file names:
red_apple5, grapes1, green_apple2, orange3
is there a way that i can convert this to an object or array something like this:
T = {"Red Apple" , "Grapes" , "Green Apple" , "Orange"}
S = {"red_apple5" , "grapes1" , "green_apple2" , "orange3"}
i want append each of them to a list. is there a way to do this?
Upvotes: 1
Views: 1820
Reputation: 8767
Assuming you want to create a valid object, utilize the following code for reference. NOTE: Some modifications were made for illustrative purposes.
HTML:
<div id="output"></div>
jQuery:
var titles = 'Red Apple, Grapes, Green Apple, Orange'.split(', ');
var fileNames = 'red_apple5, grapes1, green_apple2, orange3'.split(', ');
var newObject = {};
for(var i=0; i < titles.length; i++){
newObject [titles[i]] = fileNames[i];
}
$('#output').text(JSON.stringify(newObject));
Demo: http://jsfiddle.net/GHgsT/
The code above loops through the titles
array and then maps the titles[index]
value as the object's property (key) and the corresponding fileNames[index]
value as the property's value.
Upvotes: 1
Reputation: 6034
You can use javascript's split() method to split the string:
var str = "Red Apple, Grapes, Green Apple, Orange";
var arr = str.split(', ');
console.log(arr)
To append these to a list, you must loop through the newly created array using forEach() and then create a new li for each item. Then you can append the li as a child element to a ul.
var list = document.getElementById("#IdOfYourList")
arr.forEach(function(a) {
var newLi = document.createElement("li")
newLi.innerHTML = a;
list.appendChild(newLi);
});
Also note that forEach is not supported in IE < 8, but can be implemented into the Array prototype here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
Reference: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split
Upvotes: 2
Reputation: 869
Use .split().
var str = "Red Apple, Grapes, Green Apple, Orange";
var array = str.split(", ");
Upvotes: 1
Reputation: 254926
var array = 'Red Apple, Grapes, Green Apple, Orange'.split(', ');
Upvotes: 2