首页 > 解决方案 > 如何使用正则表达式对数组中的 Javascript 对象进行排序

问题描述

我正在调用 API 并获取包含大量对象的数组。数组中有数百个对象,其中一小段看起来像这样:

[
    {
      "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
    }
]

有没有办法使用正则表达式对数组进行排序,看起来像这样:

[
  {
    "name": "glock",
    "kills": 70,
    "shots": 1262,
    "hits": 361
  },
  {
    "name": "mac10",
    "kills": 39,
    "shots": 862,
    "hits": 261
  },
  {
    "name": "ump45",
    "kills": 136,
    "shots": 1610,
    "hits": 598
  }
]

标签: javascriptarrayssortingobject

解决方案


您可以使用reduce()方法对数组项进行分组,使用split()方法从name字符串中提取名称和操作。

var data = [{ "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 result = data.reduce((acc, curr) => {
  let words = curr.name.split('_');
  let name = words[2];
  let action = words[1];

  let item = acc.find(item => item.name === name);

  if (item) {
    item[action] = curr.value;
  } else {
    acc.push({
      "name": name,
      [action]: curr.value
    });
  }

  return acc;
}, []);

console.log(result);


推荐阅读