I have this json : name: "Andrea Rossi" I need to split the name and surname using…
- User
I have this json : name: "Andrea Rossi" I need to split the name and surname using lodash and compact in react in one line
- Assistant
lodash and compact are unnecessary for this task, as it can be accomplished with pure JavaScript in one line using the
splitmethod:codeconst [name, surname] = "Andrea Rossi".split(" ");This creates an array using the space character as the separator, and uses destructuring assignment to assign the first element to
nameand the second element tosurname. - User
i want to use join and compact and lodash, because i need to save the 2 splitted values inside name and surname
- Assistant
Sure, in that case, you could do something like this:
codeimport _ from 'lodash'; const fullName = {name: "Andrea Rossi"}; const [name, surname] = _.compact(_.split(fullName.name, ' ')); console.log(name); // "Andrea" console.log(surname); // "Rossi"Here,
_.splitsplits the full name by the space character and returns an array,_.compactremoves any falsy values (in case there are extra spaces), and the result is destructured intonameandsurname.