'convert a sentence to an object with Key/Value Format js
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
Solution 1:[1]
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)
Solution 2:[2]
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)
Solution 3:[3]
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.
Solution 4:[4]
Simple and clean
let mySentence = "12,alex \n" +"22,zac \n" +"41,sara \n" +"33,mike \n"
let sentenceObj = {}
mySentence
.split('\n') // split the string
.filter(Boolean) // filter out all empty items
.forEach(v => { // build the object
sentenceObj[v.split(',')[0]] = v.split(',')[1].trim() //key with value trimmed
});
console.log(sentenceObj);
Solution 5:[5]
try this
const a = "12,alex \n" +"22,zac \n" +"41,sara \n" +"33,mike \n";
const b = a.split('\n').reduce((prev, curr, index) => {
if(curr) {
const [key, value] = curr.split(',');
return {
...prev,
[`${key}`]: value
}
}
return prev;
}, {});
console.log(b)
Solution 6:[6]
function createObject(sentence){
let arr = sentence.split(' \n');
let obj = {};
arr.forEach(ai => {
let parsed = ai.split(',')
if (parsed.length == 2) {
obj[parsed[0]] = parsed[1];
}
})
return obj
}
let sentence = "12,alex \n" + "22,zac \n" + "41,sara \n" + "33,mike \n";
console.log(createObject(sentence));
You can use the above function for conversion
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 | ruleboy21 |
| Solution 2 | Tanay |
| Solution 3 | Reznov |
| Solution 4 | Pellay |
| Solution 5 | Rogelio |
| Solution 6 | Parth Sharma |
