Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort Javascript objects in an array using regex

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
  }
]
like image 544
Leon Avatar asked Dec 22 '22 21:12

Leon


1 Answers

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);
like image 121
Nick Avatar answered Jan 05 '23 00:01

Nick