简体   繁体   English

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

[英]javascript - Parse string to JSON object

Sorry, a little new to this. 对不起,这个有点新鲜。 But I am trying to achieve the following. 但我正在努力实现以下目标。 I have this (the fullName string is returned from a webapp UI using selenium webdriverIO): 我有这个(使用selenium webdriverIO从webapp UI返回fullName字符串):

const fullName = "Mr Jason Biggs";

And need it to look like this: 并且需要它看起来像这样:

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

I tried splitting the name, but not sure how to add ak to the v 我尝试拆分名称,但不知道如何将v添加到v

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

Just create a new object and assign those splitted parts to its keys: 只需创建一个新对象并将这些拆分部分分配给其键:

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

If you have a lot of strings that needs this work to be done, then just wrap the code in a function getObject that takes a string and returns the 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)); 

If you want to get fancy and use newer syntax, you can use destructuring assignment as well: 如果您想获得更多花哨并使用更新的语法,您也可以使用解构赋值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM