Austin Hoh Austin Hoh - 25 days ago 7
Javascript Question

How to convert an array into an array object in javascript?

My scenario is where i will upload a text file contain data like this

a1,b1,,c1,d1,
a2,b2,,c2,d2,


From the data, i able read and split it with ("\n") and result is

array=[array[0]:[a1,b1,,c1,d1]
array[1]:[a2,b2,,c2,d2]]


How can i populate the array above into my array object?

sample output:

newarray=[[name="a1",age:"b2",address="",contact="c1",gender="d1"],
[name="a2",age:"b2",address="",contact="c2",gender="d2"]]

Answer

As the position of each attribute in the array seems to be fixed, i would just create a function with a fixed assignment. Like 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