抱歉,这有点新。但我正在努力实现以下目标。我有这个(使用硒webdriverIO从Webapp UI返回fullName字符串):

const fullName = "Mr Jason Biggs";


并需要它看起来像这样:

title: 'Mr',
name: 'Jason',
surname: 'Biggs',


我尝试拆分名称,但不确定如何将v添加到k

const splitName = fullName.split(" ");
// But returns as [ 'Mr', 'Jason', 'Biggs' ]

最佳答案

只需创建一个新对象并将这些分割的部分分配给其键即可:



const fullName = "Mr Jason Biggs";

const splitName = fullName.split(" "),
      object = {
          title: splitName[0],
          name: splitName[1],
          surname: splitName[2]
      };

console.log(object);





如果您有很多需要完成此工作的字符串,则只需将代码包装在函数getObject中,该函数接受一个字符串并返回该对象:



function getObject(str) {
    const splitName = str.split(" ");
    return {
        title: splitName[0],
        name: splitName[1],
        surname: splitName[2]
    };
}


const arrayOfStrings = ["Mr Jason Biggs", "Dr Stephen Strange", "Ms Lilly Depp"];

console.log(arrayOfStrings.map(getObject));

10-07 14:22