'How do I convert a string with a first name and last name to an object w/ properties of {firstName: "string first name", lastName: "string last name}?
function convertNameToObject(string) {
let obj = {};
obj.firstName = ;
obj.lastName = ;
return obj;
}
console.log(convertNameToObject("Harry Potter"));
Solution 1:[1]
Just split on the space character.
function convertNameToObject(string) {
const [firstName, lastName] = string.split(" ");
return { firstName, lastName };
}
console.log(convertNameToObject("Harry Potter"));
Solution 2:[2]
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"));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
