javascript - 将字符串解析为JSON对象

时间:2017-06-23 14:40:09

标签: javascript json

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

const fullName = "Mr Jason Biggs";

需要它看起来像这样:

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

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

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

2 个答案:

答案 0 :(得分:2)

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



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




答案 1 :(得分:1)

如果您想要使用更新的语法,可以使用destructuring assignment

    const fullName = "Mr Jason Biggs";

    // Split and assign to named vars
    const [title, name, surname] = fullName.split(' ');
    // Create object from the new vars with the property value shorthand
    const obj = {
      title,
      name,
      surname
    };
    
    console.log(obj);