0

I have a string as

string = "name: my name 
           email: myemail
           address: my address";

Which will paste by the user.
Now I want it to convert in object such that

obj = {"name":"my name", "email":"myemail", "address":"my address"}

How can I do this in JS?

I already tried this String to object in JS but this only works when theres a comma separator.

Patrick W
  • 1,485
  • 4
  • 19
  • 27
exia
  • 3
  • 3

3 Answers3

0

The easiest way to fix this issue would be to nip it at the bud - send the object not a string. If that's not possible, then use split and reduce on the multiline string:

const string = `name: my name 
email: myemail
address: my address`;
const res = string.split("\n").map(e => e.split(":").map(f => f.trim())).reduce((a, [k, v]) => ({ ...a, [k]: v }), {});
console.log(res);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

You can use the ECMAScript 2019 Object.fromEntries() function:

const string = "name: my name\nemail: myemail\naddress: my address";

const object = Object.fromEntries(string.split(/\n/).map(s => s.split(/: /)));

console.log(object);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

Sounds like a little coding challenge :)

const convertStrToObj = (str) =>
str.split('\n').reduce((result, field) => {
  const splitField = field.split(':')
  const fieldName = splitField[0].trim()
  const fieldValue = splitField[1].trim()
  return {
    ...result,
    [fieldName]: fieldValue
  }
}, {})
Zico Deng
  • 645
  • 5
  • 14