【问题标题】:JavaScript count the number of times a specific value is mentioned in an array of objects [duplicate]JavaScript计算对象数组中提到特定值的次数[重复]
【发布时间】:2021-11-01 14:08:32
【问题描述】:

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

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

谢谢 乔治

【问题讨论】:

  • const count = Object.entries(output.reduce((acc,cur) =&gt; { const name= cur["Software Name"]; acc[name] = acc[name] || 0; acc[name]++; return acc;},{})).map(([key,val]) =&gt; ({ [key]:val }))
  • @mplungjan 谢谢,这部分有效。我的 json 输出中还有其他元素,当我返回它时,这些元素会在计数中返回。
  • 然后先过滤
  • 我不完全确定该怎么做

标签: javascript json object nested


【解决方案1】:

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

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

【讨论】:

  • 这很好,但是,它没有正确计数
  • 你是对的。我修好了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-24
  • 1970-01-01
  • 2018-09-22
  • 2021-01-02
  • 2013-06-03
  • 2022-01-11
相关资源
最近更新 更多