0

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"]]
2

2 Answers 2

2

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]
  };
}

Sign up to request clarification or add additional context in comments.

Comments

0

function arrToObj(arr){
 var newArr = [];
 arr.forEach(function(value,index){
     obj = {};
     obj.name = value[0];
     obj.age = value[1];
     obj.contact = value[2];
     newArr.push(obj);

});
return newArr;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.