Home > Blockchain >  How do I convert a string with a first name and last name to an object w/ properties of {firstName:
How do I convert a string with a first name and last name to an object w/ properties of {firstName:

Time:05-21

function convertNameToObject(string) {

    let obj = {};
    obj.firstName = ;
    obj.lastName = ;
    return obj;

}
console.log(convertNameToObject("Harry Potter"));

CodePudding user response:

Just split on the space character.

function convertNameToObject(string) {
    const [firstName, lastName] = string.split(" ");
    return { firstName, lastName };
}
console.log(convertNameToObject("Harry Potter"));

CodePudding user response:

Little improved version that originally was provided by @Samathingamajig.

In the body of function there is IIFE expression.

function convertNameToObject(string) {
    return (([firstName, lastName]) => ({firstName, lastName}))(string.split(" "))

}
console.log(convertNameToObject("Harry Potter"));

  • Related