首页 > 解决方案 > JavaScript 计算对象数组中特定值被提及的次数

问题描述

我正在寻找一个解决方案来解决我目前在循环包含对象的数组时遇到的问题。在我想访问第二个元素 [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 比较陌生。如果需要更多信息,请告诉我。

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

谢谢乔治

标签: javascriptjsonobjectnested

解决方案


在这里使用对象比数组更有用来保存数据。但如果需要,您可以转换。

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 );


推荐阅读