Dyana Putry Dyana Putry - 3 months ago 8
Javascript Question

How do I change the array string into an array of objects in javascript?

Suppose I have the data I write into the variable

str


var str = "Volvo,Saab,Mercades,Audi";
// document.write(typeof str+"<br/><br/>"); => string
// document.write(str[0]+"<br/>"); => V
// document.write(str[1]+"<br/>"); => o

var obj = ["Volvo","Saab","Mercades","Audi"];
// document.write(typeof obj+"<br/><br/>"); => object
// document.write(obj[0]+"<br/>"); => Volvo
// document.write(obj[1]+"<br/>"); => Saab


How do I change the
str
variable into an array of types of objects, such as the variable
obj
?

Answer

Simply use str.split(',')

var str = "Volvo,Saab,Mercades,Audi";
var arr = str.split(',');
console.log(arr);
Comments