I'm making a call to an API and getting an array with large amounts of objects. There are hundreds of objects in the array and a short snippet of it looks something like this:
[
{
"name": "total_kills_glock",
"value": 70
},
{
"name": "total_kills_mac10",
"value": 39
},
{
"name": "total_kills_ump45",
"value": 136
},
{
"name": "total_shots_glock",
"value": 1262
},
{
"name": "total_hits_glock",
"value": 361
}
{
"name": "total_shots_mac10",
"value": 862
},
{
"name": "total_hits_mac10",
"value": 261
},
{
"name": "total_shots_ump45",
"value": 1610
},
{
"name": "total_hits_ump45",
"value": 598
}
]
Is there a way to sort the array using regex to look something like this:
[
{
"name": "glock",
"kills": 70,
"shots": 1262,
"hits": 361
},
{
"name": "mac10",
"kills": 39,
"shots": 862,
"hits": 261
},
{
"name": "ump45",
"kills": 136,
"shots": 1610,
"hits": 598
}
]
Here's one way to do it, using regex to extract the name and data type from the raw name, and then building an object based on that:
const raw = [{
"name": "total_kills_glock",
"value": 70
},
{
"name": "total_kills_mac10",
"value": 39
},
{
"name": "total_kills_ump45",
"value": 136
},
{
"name": "total_shots_glock",
"value": 1262
},
{
"name": "total_hits_glock",
"value": 361
},
{
"name": "total_shots_mac10",
"value": 862
},
{
"name": "total_hits_mac10",
"value": 261
},
{
"name": "total_shots_ump45",
"value": 1610
},
{
"name": "total_hits_ump45",
"value": 598
}
];
var final = [];
var keys = [];
raw.forEach(v => {
const m = v.name.match(/^total_([^_]+)_(.+)$/);
const k = keys.indexOf(m[2]);
if (k == -1) {
var o = { name: m[2] };
o[m[1]] = v.value;
final.push(o);
keys.push(m[2]);
} else {
final[k][m[1]] = v.value;
}
});
console.log(final);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With