1

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

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 a k to the v

const splitName = fullName.split(" ");
// But returns as [ 'Mr', 'Jason', 'Biggs' ]
3
  • arr = ['Mr', 'Jason', 'Biggs']. beautiful_name = { title: arr[0], name: arr[1], surname: arr[2] } Commented Jun 23, 2017 at 14:42
  • add a k to the v? What do you mean? Anyway you can do { title:splitName[0], name:splitName[1], surname:splitName[3] } Commented Jun 23, 2017 at 14:43
  • JSON is a text format; you appear to want a data structure in the JavaScript execution environment, not a JSON-serialized string that represents an object. (In other words: you want to create an "object" not a "JSON object".) JSON serialization doesn't appear to have anything to do with your goal here. You you really do want a JSON string, you need to take the existing answers and pass their result into JSON.stringify Commented Jun 23, 2017 at 14:46

2 Answers 2

2

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:

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

I just wanted to post the same answer (using object literal property name shorthand). I'm glad someone had the same idea. Take my upvote.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.