JavaScript 计算特定值在对象数组中被提及的次数

JavaScript count the number of times a specific value is mentioned in an array of objects

我正在寻找一个问题的解决方案,以解决我目前在遍历包含对象的数组时遇到的问题。在子对象中,我想访问第二个元素 [2],在下面的示例中取其值;

windows, windows_11, linux_sys

检查它们当前是否存在于一个数组中(数组开始为空,因此如果它们不存在,它会将值附加到其中,并计算特定“软件名称”在所有子项中出现的次数对象。

这是我的 JSON 数组的示例输入以及我目前拥有的:

json_output = [
  {
    "id": "1",
    "Device Name": "device3",
    "Software Name": "windows"
  },
  {
    "id": "2",
    "Device Name": "device6",
    "Software Name": "windows"
  },
  {
    "id": "3",
    "Device Name": "device11",
    "Software Name": "windows"
  },
  {
    "id": "4",
    "Device Name": "device11",
    "Software Name": "windows_11"
  },
  {
    "id": "5",
    "Device Name": "device11",
    "Software Name": "linux_sys"
      }
   ]

new_arr = [];

for (var i = 0; i < json_output.length; i++) {
    new_arr.push(Object.values(json_output[i])[2]);
}

这将返回一个列表,其中包含:

["windows","windows","windows", "windows_11", "linux_sys"]

如果有人能帮助我创建下方,我将不胜感激。而不是我目前拥有的数组,我很想重新创建下面的数组;

   software_name_count [
      {
        "windows": "3"
      },
      {
        "windows_11": "1"
      },
      {
        "linux_sys": "1"
      }
    ]

感谢任何帮助我解决这个问题的人。我对 JS 比较陌生。如果需要更多信息,请告诉我。

p.s。我无法对这段代码的任何部分进行硬编码,例如软件名称 windows、windows_11 和 linux_sys.

谢谢 乔治

这里使用对象比数组更有用来保存数据。但您可以根据需要进行转换。

json_output = [
  {
    "id": "1",
    "Device Name": "device3",
    "Software Name": "windows"
  },
  {
    "id": "2",
    "Device Name": "device6",
    "Software Name": "windows"
  },
  {
    "id": "3",
    "Device Name": "device11",
    "Software Name": "windows"
  },
  {
    "id": "4",
    "Device Name": "device11",
    "Software Name": "windows_11"
  },
  {
    "id": "5",
    "Device Name": "device11",
    "Software Name": "linux_sys"
  }
];

new_obj = {};

for (obj of json_output) {
  let key = obj["Software Name"];
  new_obj[key] = json_output.filter(a => a["Software Name"] == key).length;
}

console.log( new_obj );

// do you need to format this as an array? if so, do this

const new_arr = [];
for (const [softwareName, count] of Object.entries(new_obj)) {
  let row = {[softwareName]: count};
  new_arr.push(row);
}

console.log( new_arr );