i have array of object where some key values are set in comma seperated
here below is sample object how it is
var data = [{
"id":1,
"x, y, z" :"1,2,3"
}, {
"id":2,
"x, y, z" :"10,12,153"
}, {
"id":3,
"x, y, z" :"9,8,5"
}, {
"id":4,
"x, y, z" :"14,87,13"
}]
here is the expected output
[{
"id":1,
"x":1,
"y":2,
"z":3
},{
"id":2,
"x":10,
"y":12,
"z":153
},{
"id":3,
"x":9,
"y":8,
"z":5
},{
"id":4,
"x":14,
"y":87,
"z":13
}]
here below is code i tried,
const outputArray = data.map((item:any, index:number) => {
let commaHeaders = Object.keys(item)[index]?.split(',');
console.log(commaHeaders)
if(commaHeaders && commaHeaders.length >= 2) {
commaHeaders.map((comma) =>{
item[comma] = comma.trim();
})
}
return item
});
Note
the function should be generic, in some case i will get a,b,c as a key values instead of x,y,z
any help or suggestions are really helpful!
3
Answers
Something like:
This doesn’t automatically cast the values to Numbers, but you can trivially add that.
You could split all key/value pairs (by comma with optional whitespace) and convert finite values to numbers.
Something like this should work