I have a sentence like below:
mySentence = "12,alex \n" +"22,zac \n" +"41,sara \n" +"33,mike \n"
and want to convert into an object like below:
{
"12":"alex",
"22":"zac",
"41":"sara",
"33":"mike"
}
any solution would be my appreciated
Try this
var mySentence = "12,alex \n" +"22,zac \n" +"41,sara \n" +"33,mike \n"
mySentence = Object.fromEntries(mySentence.trim().split(' \n').map(v => v.split(',')))
console.log(mySentence)
You can try this:
const mySentence = "12,alex \n" +"22,zac \n" +"41,sara \n" +"33,mike \n";
const object = {};
mySentence.split('\n').filter(e => e != '').forEach(e => {
const str = e.trim().split(',')
const key = str[0];
const value = str[1];
object[key] = value;
});
console.log(object)
You could use a package like QS or https://www.npmjs.com/package/url-search-params-polyfill to support any browsers like IE and Node.js as well.