Convert response string to object

I want this response: "socials": "Whatsapp_phone: 3413536723,Instagram: agusmac1,Linkedin: agusmac,Facebook: agusmac40"

to be something like:

 socials={
Whatsapp: 3413536723,
Instagram: agusmac1,
Linkedin: agusmac,
Facebook: agusmac20}

ive tried JSON parse but i cant make it work

Answer

You can first parse the string into an object by wrapping the string in curly braces and using JSON.parse.

Then, you can split the resulting object’s socials property by a comma, split each individual item by a colon (with map), then use Object.fromEntries:

const str = `"socials": "Whatsapp_phone: 3413536723,Instagram: agusmac1,Linkedin: agusmac,Facebook: agusmac40"`

const obj = JSON.parse('{' + str + '}')
obj.socials = Object.fromEntries(obj.socials.split(",").map(e => e.split(":")))

console.log(obj)

If you want the value to be trimmed, you can use String.trim():

const str = `"socials": "Whatsapp_phone: 3413536723,Instagram: agusmac1,Linkedin: agusmac,Facebook: agusmac40"`

const obj = JSON.parse('{' + str + '}')
obj.socials = Object.fromEntries(obj.socials.split(",").map(e => (arr = e.split(":"), arr[1] = arr[1].trim(), arr)))

console.log(obj)