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}
]
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);
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}
Observations :
values property it should be tag.array of elements. This splitarr[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);