How to convert an array into an array object in javascript? -
my scenario upload text file contain data this
a1,b1,,c1,d1, a2,b2,,c2,d2,
from data, able read , split ("\n") , result is
array=[array[0]:[a1,b1,,c1,d1] array[1]:[a2,b2,,c2,d2]]
how can populate array above array object?
sample output:
newarray=[[name="a1",age:"b2",address="",contact="c1",gender="d1"], [name="a2",age:"b2",address="",contact="c2",gender="d2"]]
as position of each attribute in array seems fixed, create function fixed assignment. this:
var str = "a1,b1,,c1,d1,\na2,b2,,c2,d2,"; var objects = parsestring(str); console.log(objects); function parsestring(strin){ var objectlist = []; var splitresult = strin.split("\n"); for(var i=0;i<splitresult.length;i++){ var valuearray = splitresult[0].split(","); objectlist.push(maptoobject(valuearray)); } return objectlist; } function maptoobject(array){ return { name: array[0], age:array[1], address: array[2], contact: array[3], gender:array[4] }; }
Comments
Post a Comment