Organize items based on the values of a specific key within a JavaScript object

I have a collection of items as follows:

[{
        "id": "123",
        "title": "Article 1",
        "evaluationLevel": {
            "levelName":A
        },
        "category": ["Category 1", "Category 2", "Category 3"]
    },
    {
        "id": "234",
        "title": "Article 2",
        "evaluationLevel": {
            "levelName":B 
        },
        "category": ["Category 2", "Category 4"]
    },
    {
        "id": "567",
        "title": "Article 3",
        "evaluationLevel": {
            "levelName":C
        },
        "category": ["Category 1"]
}]

I'm looking to organize this data in the following way:

{
   "Category 1": [
      ["1", "Article 1", A],
      ["2", "Article 3", C]

   ],
   "Category 2": [
      ["3", "Article 1", A],
      ["4", "Article 2", B]

   ],
   "Category 3": [
      ["5", "Article 1", A]

   ],
   "Category 4": [
      ["6", "Article 2", C]
   ]
}

Is there a more efficient method for sorting and grouping objects like this using JavaScript? I came across a helpful discussion on How to group an array of objects by key. However, my case requires grouping based on values within the category object.

Answer №1

If you want to categorize your array and then add an index to it, consider using the array#reduce method. This will help you group the elements based on categories.

let index = 0;
const data = [{ "id": "123", "title": "Article 1", "evaluationLevel": { "levelName": 'A' }, "category": ["Category 1", "Category 2", "Category 3"] }, { "id": "234", "title": "Article 2", "evaluationLevel": { "levelName": 'B' }, "category": ["Category 2", "Category 4"] },{ "id": "567", "title": "Article 3", "evaluationLevel": { "levelName": 'C' }, "category": ["Category 1"] }],
      result = data.reduce((r,o,i) => {
        o.category.forEach((category, j) => {
          r[category] = r[category] || [];
          r[category].push([o.title, o.evaluationLevel.levelName])
        });
        return r;
      },{}),
      output = Object.keys(result).reduce((r,k) => {
        result[k].forEach((item) => {
          index++;
          r[k] = r[k] || [];
          r[k].push([index, ...item]);
        });
        return r;
      }, {})
console.log(output);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Execute a node script file at random intervals

I've been utilizing forever to maintain the continuous execution of a node script: forever start script1.js However, my requirement is to run these files in a random order... For instance: Execute node script1.js Execute node script2.js Run script ...

Is it advisable to employ multiple websocket connections for achieving parallel communication?

Imagine one person is in charge of managing a substantial amount of chart data. Meanwhile, another individual is responsible for updating user information. Is this arrangement suitable? I am uncertain how the concept of JavaScript being single-threaded w ...

Why won't NextJS Image elements render on iOS 16 when they are not in the viewport initially?

I opted to implement NextJS for enhanced routing capabilities and image optimization. However, I encountered an issue with certain images failing to load properly on iOS devices. The problem arises within a scrollable horizontal container featuring Product ...

Understanding Javascript Scoping

<html> <head> <title></title> <script type="text/javascript"> var x = 1; function y() { x = 10; return; function z() {} } </script> </head> <body> <script type="text/javascri ...

Setting up a service URL with parameters using a versatile approach

I am faced with a situation where I have over 200 service URLs that follow a specific format: serviceURL = DomainName + MethodName + Path; The DomainName and MethodNames can be configured, while the path may consist of elements such as Param1, Param2, an ...

Detecting the State of the Keyboard in Ionic 2

Seeking an easy way to determine if the mobile device keyboard has been opened or closed using Ionic2 and Angular2. Is there a 'keyboard-open' or 'keyboard-close' class that Ionic sends to the body/html? ...

Tips for handling spaces in JSON arrays when parsing data in Ansible

Here is the JSON data I am working with: { "changed": false, "invocation": { "module_args": { "cucm_ip": "1.1.1.1", "cucm_option": "DBREPLICATION", "cucm_pwd": "123", "cucm_user": "123" ...

Errors and disruptions caused by SmoothScroll, ScrollMagic, and GSAP triggering glitches, jumps, and crashes

Connecting ScrollMagic with GSAP is not an issue - it works seamlessly. However, I encountered a problem when trying to implement smooth scrolling for my mouse. I added a smooth scrolling plugin to my project from this link: http://www.jqueryscript.net/ani ...

Splicing using only one parameter will make changes to the array without deleting the entire array

let myArray = ['a','b','c','d','e']; console.log(myArray.splice(1)); console.log(myArray); Looking at the splice documentation, it mentions that not providing a delete parameter would remove all array item ...

Understanding the process of reading cookies on the Angular2 side that have been set by the C# server

I'm struggling to understand how the angular code can access the cookie that was set on the server side. I found the following code snippet on GitHub. This C# function sets the cookie in the Response object with the last line of code. My question is, ...

jquery-edit-in-place

Recently, I started using the edit-in-place plugin available at: I am impressed by its performance! However, I am facing a challenge. I need to implement a function that checks if the new text entered is empty. If it is empty, I want to display an error a ...

How can I track the source of inbound network traffic using node.js and express?

Currently, I'm attempting to make use of railway's latest app sleeping feature that automatically puts your active deployment to sleep after 10 minutes of no outbound network activity. This feature then wakes up your server upon receiving any inb ...

The method to update the shopping cart quantity count without needing to refresh the page or navigate to a separate page

One issue I am facing is with the code that displays a live count of items in the shopping cart. It doesn't update instantly, requiring a page reload or navigation to another page for the changes to be visible. The current code is implemented on a pa ...

Is it possible to create tags in Material UI Autocomplete using events other than just pressing the 'Enter' key?

In my current project, I am utilizing the freesolo Autocomplete feature. My specific requirement is to create tags when input text is followed by commas or spaces. Currently, tags are created on the Enter event by Autocomplete, but I am looking for a way t ...

Preview multiple images while uploading in a React JS application

In order to achieve multiple image upload with preview using React JS, I attempted the code below. However, I encountered an error in the console: Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This ...

What is the best method to determine the variance between two arrays in PHP?

Take a look at array 1 below: Array ( [ABC01] => 10.123.456.78 [ABC02] => 10.123.456.79 [ABC03] => 10.123.456.80 [ZYX99] => 10.123.456.81 ) Now, here is array 2: Array ( [0] => ABC01 [1] => ABC02 ...

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...

Having trouble receiving the $_POST array after submitting a form in PHP 5.6. Looking for a solution?

Need a form with the method of post, please see below: <form action="/includes/process.php" method="post"> <input type="hidden" name="breakDown" value="1" /> <input type="hidden" name="string" value="2" /> <a href ...

Looking to dissect JSON output containing the object labeled as "@attributes"?

Using JQuery AJAX, I made an HTTP request to a PHP back-end in order to retrieve an XML string parsed into JSON using the json_encode() function. Some of the XML elements contain attributes which are represented as @attributes in the output. However, when ...

Is there a method to merge elements from two separate "lists of lists" that contain the same elements but have different lengths within each list?

In an attempt to merge two distinct lists of lists based on shared elements, I find myself faced with a challenge. Consider the following: list1 = [['a1', 'a2', 'b2'], ['h1', 'h2'], ['c1', ' ...