如何return对象的名字和姓氏

How to return object of first and last names

结果是 returning {名字:'Mike,Henry,Pete',姓氏:'Port,Split,Micky'} 我想要结果 return { 名字:迈克, 姓氏:港口 }, { 名字:亨利, 姓氏:斯普利特 }, { 名字:皮特, 姓氏:米奇 }

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);

", " 拆分数据然后用 " "

拆分
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);

代码如下:

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))

你可以在一行中结合 String#split() with Array#map() and Destructuring assignment

代码:

const data = 'Mike Port, Henry Split, Pete Micky'
const result = data
  .split(', ')
  .map(s => s.split(' '))
  .map(([firstname, lastname]) => ({ firstname, lastname }))
  
console.log(result)

在 long-term 中最好不要在代码中指定键。如果要向数据添加一个名为 age 的新 属性 会怎样?这将意味着必须进入代码并更新它以适应变化,这是一个麻烦。

此示例通过跟踪键并循环遍历键和值来创建新数据集,从而消除了这种复杂性。任何地方都没有 hard-coding 个键。

const data = {
  firstname: 'Mike,Henry,Pete',
  lastname: 'Port,Split,Micky',
  age: '10,100,20',
  location: 'France,Germany,Iceland',
  role: 'chef,musician,writer',
  tree: 'larch,maple,oak'
};

// Get the keys and values from the object
const keys = Object.keys(data);
const values = Object.values(data).map(str => str.split(','));

// Temporary array
const out = [];

// Loop over the first array in the values array
for (let i = 0; i < values[0].length; i++) {

  // Initialise an empty object
  // for each nested array
  const obj = {};
  
  // Loop over the keys, create a new object with
  // that key, and the element of the nested value array
  // and merge it with the object
  for (let j = 0; j < keys.length; j++) {
    const prop = { [keys[j]]: values[j][i] };
    Object.assign(obj, prop);
  }

  // Push the object to the array
  out.push(obj);

}

console.log(out);

其他文档