'split the string and convert to array of objects javascript
I have a string data, I need to convert to array of objects in javascript
Below the code tried
var splitarr = sample.split('|');
var result = splitarr.map(e=>{
details: e,
values: splitarr[e]
})
var sample = "finance=60|IT=88|sales=50"
Expected Output
[
{"details": "finance","tag":60},
{"details": "IT","tag":88},
{"details": "sales","tag":50}
]
Solution 1:[1]
You need another split by =, try:
var sample = "finance=60|IT=88|sales=50";
var splitarr = sample.split('|');
var result = splitarr.map(e=>{
let keyVal = e.split('=');
return { details: keyVal[0], tag:keyVal[1] }
})
console.log(result);
Also when you return object from arrow function you neeed to use brackets (), otherwise it will be considered as block of code, try:
var sample = "finance=60|IT=88|sales=50";
var splitarr = sample.split('|');
var result1 = splitarr.map(e=>{
details: e
})
console.log(result1);
var result2 = splitarr.map(e=>({
details: e
}))
console.log(result2);
Solution 2:[2]
Another way of transforming string to object.
const sample = "finance=60|IT=88|sales=50";
const result = sample
.split('|')
.map((e) => e.split('='))
.map(([details, tag]) => ({ details, tag }));
console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}
Solution 3:[3]
Use regex to extract all pairs eg. "finance=60" by using string.match(regex) which will return array of pairs and then use Array.map() to map into array of objects.
const text = "finance=60|IT=88|sales=50";
const convertToObject = (str) => {
const list = str.match(/\w+=\d+/g);
return list.map(ele => {
const [details, tag] = ele.split("=");
return { details, tag };
});
}
console.log(convertToObject(text));
Solution 4:[4]
Observations :
- Instead of
valuesproperty it should betag. - As splitter will be a simple
arrayof elements. Thissplitarr[e]will not work or not exist.
You can use String.split() method to get the details and tag value.
Working Demo :
const sample = "finance=60|IT=88|sales=50";
const splitarr = sample.split('|');
const result = splitarr.map((e) => {
return {
details: e.split('=')[0],
tag: e.split('=')[1]
}
});
console.log(result);
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 | mickl |
| Solution 2 | |
| Solution 3 | Rahul Kumar |
| Solution 4 | Rohìt JÃndal |
