Dyana Putry Dyana Putry - 1 year ago 55
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


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
variable into an array of types of objects, such as the variable

Answer Source

Simply use str.split(',')

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