Home > Net >  How to return object of first and last names
How to return object of first and last names

Time:05-24

The result is returning {firstname: 'Mike,Henry,Pete', lastname: 'Port,Split,Micky'} I want result to return { firstName: Mike, lastName: Port }, { firstName: Henry, lastName: Split }, { firstName: Pete, lastName: Micky }

var data = "Mike Port, Henry Split, Pete Micky";
var firstName = [];
var lastName = [];
var result = [];
var newNames = data.replaceAll(", ", ",");
var fullName = newNames.split(',');
fullName.forEach(name => {
  let splitted = name.split(" ");
  firstName.push(splitted[0]);
  lastName.push(splitted[1]);
});

f_name_list = firstName.toString().split(", ");
l_name_list = lastName.toString().split(", ");

for (let i = 0; i < f_name_list.length; i  ) {
  result.push({ 
    firstname: f_name_list[i],
    lastname: l_name_list[i]
  });
}

console.log(result);

CodePudding user response:

split data with ", " then split with " "

var data = "Mike Port, Henry Split, Pete Micky";
var result = [];
var newNames = data.split(", ");
newNames.forEach(name => {
  let splitted = name.split(" ");
  result.push({ 
    firstname:splitted[0],
    lastname: splitted[1]
  });
});

console.log(result);

CodePudding user response:

Here is the code:

var data = "Mike Port, Henry Split, Pete Micky";

function parseData(data){
  data = data.split(', ')
  let arr = []
  for(i=0;i<data.length;i  ){
    arr.push({firstName:data[i].split(' ')[0].replace(',',''),lastName:data[i].split(' ')[1]})
  }
  return arr
}
console.log(parseData(data))
  • Related