0

I am looking for a solution to an issue I am currently experiencing with looping over an array containing objects. Within the child objects I would like to access the second element [2], take its value in my example beneath;

windows, windows_11, linux_sys

Check whether they current exist within an array (array starts empty therefore it'll append the values into it if they don't already exist, and count the number of times a specific "Software Name" occurs in all child objects.

Here is an example input of my JSON array and what I currently have:

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

This is returning a list containing:

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

If anyone could help me create the beneath I would greatly appreciate it. Instead of a array as I currently have, I'd quite like to recreate the beneath;

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

Thank you to anyone that assists me with conquering this problem. I'm relatively noobish with JS. If there's any more information that's required please let me know.

p.s. I cannot hard code any section of this code, such as the software names windows, windows_11 and linux_sys.

Thanks George

1 Answers1

0

Using an object is more useful than an array here to save the data. But you can convert if need be.

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 );
code_monk
  • 9,451
  • 2
  • 42
  • 41