In: Computer Science
Hi, I need to finish function purser,which will include header row and i can get same output
/*
[
{ firstName: 'moe', lastName: 'green' },
{ firstName: 'lucy', lastName: 'liu' },
{ firstName: 'ethyl', lastName: 'mertz' }
]*/
In javascript please
const parser=(d)=>{
let arr=[];
let newArr=[];
let obj={}
let items=d.split('|');
for (let i=0;i<items.length;i++){
arr[i]=items[i].split(',');
}
for (let z=0;z<arr.length;z++){
newArr=newArr.concat(arr[z]);
}
for(var y = 0;y < newArr.length;y+=2){
obj[newArr[y]]= newArr[y+1];
}
//const res = newArr.reduce((a,b)=> (a[b]='',a),{});
return obj;
}
const data = `firstName, lastName | moe, green|lucy, liu|ethyl, mertz`;
console.log(parser(data));
/*
[
{ firstName: 'moe', lastName: 'green' },
{ firstName: 'lucy', lastName: 'liu' },
{ firstName: 'ethyl', lastName: 'mertz' }
]*/
Below is the correct code to parse the input and output the data in required mentioned format : -
There are some modification done in the above provided code to make it correct , see below code-
===============================CODE START =====================================
const parser=(d)=>{
let arr=[];
let newArr=[];
let finalarry = []; /* Declared to store the final output , as output needs to be in array of objects format*/
let items=d.split('|');
for (let i=0;i<items.length;i++){
arr[i]=items[i].split(',');
}
/* Modification in below loop , as now it start from index 1 , because in array - arr[0] position headers are present */
for (let z=1;z<arr.length;z++){
newArr=newArr.concat(arr[z]);
}
/* Modification in below loop */
for(var y = 0;y < newArr.length;y+=2){
let obj={} ; /* define obj
within loop */
obj[arr[0][0]] = newArr[y]; /*
arr[0][0] and arr[0][1] contains the header name
*/
obj[arr[0][1]] = newArr[y+1];
finalarry.push(obj); /*
push the created object in final array */
}
//const res = newArr.reduce((a,b)=> (a[b]='',a),{});
return finalarry; /* return the final array */
}
const data = `firstName, lastName | moe, green|lucy, liu|ethyl, mertz`;
console.log(parser(data));
=============================CODE END===============================================
Please comment if any query!