Transforming a JSON array from one structure to another with the power of JavaScript

Hello everyone, I'm new to this platform and seeking some advice. Can anyone help me with converting a JSON array to another JSON array while grouping by ID and including only the values of 'ID' and 'SID'? I've attempted using lodash and array.reduce but haven't been able to achieve the desired outcome. The input will consist of a large JSON array, so any tips on efficiently solving this problem would be greatly appreciated. Input:

[
    {
        "id": "11111",
        "sid": "12345"
    },
    {
        "id": "22222",
        "sid": "23456"
    },
    {
        "id": "22222",
        "sid": "34567"
    }
]

Expected Output:

[
    {
        "11111": [
            "12345"
        ]
    },
    {
        "22222": [
            "23456",
            "34567"
        ]
    }
]

Lodash Method:

_.groupBy(array, x => x.id);

Output Using Lodash:

{
  '11111': [
    { id: '11111', sid: '12345' }
  ],
  '22222': [
    { id: '22222', sid: '23456' },
    { id: '22222', sid: '34567' } 
  ]
}

Using Array Reduce Method:

const groupById = (array, key, value) => {
  return array.reduce((result, currentValue) => {
    (result[currentValue[key]] = result[currentValue[key]] || []).push(
      currentValue[value]
    );
    return result;
  }, {});
};

Output Using Array Reduce Method:

{
    "11111": [
        "12345"
    ],
    "22222": [
        "23456",
        "34567"
    ]
}

Answer №1

To group objects using a specific key and retrieve the values later, you can store the object with the desired key for grouping.

const
    data = [{ id: "11111", sid: "12345" }, { id: "22222", sid: "23456" }, { id: "22222", sid: "34567" }],
    result = Object.values(data.reduce((r, { id, sid }) => {
        r[id] ??= { [id]: [] };
        r[id][id].push(sid);
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To group the values based on their `id`, you can utilize the `Array.prototype.reduce` function to organize them and then retrieve the grouped values by employing the `Object.values` function.

const records = [{ id: "11111", sid: "12345" }, { id: "22222", sid: "23456" }, { id: "22222", sid: "34567" }],
      outcome = Object.values(records.reduce((accumulator, { id, sid }) => {
          (accumulator[id] || (accumulator[id] = {[id]: []}))[id].push(sid);
          return accumulator;
      }, {}));

console.log(outcome);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

The jQuery Validate Plugin only validates emails when the user moves away from the input field

Resolved: Upon inspecting my version of jquery-validate.js, I discovered that it was missing the onkeyup handler. Despite using version 1.12 Opre, which should have had this functionality according to its Github history from 2013, it seemed like there may ...

What could be causing SVG to not render in a NEXTJS project upon deployment on Vercel?

Recently, I created a standout single-page nextJS application that was beautifully styled with Tailwind CSS. One interesting feature I added was incorporating the background of a component called SectionWrapper as an svg file. To achieve this, I crafted a ...

Unable to insert the string into the database: BaseXException: Name '' is considered invalid

Once I successfully input valid XML from a file into BaseX, how can I now add valid XML from a String? thufir@dur:~/NetBeansProjects/twitterBaseX$ thufir@dur:~/NetBeansProjects/twitterBaseX$ basex BaseX 9.0.1 [Standalone] Try 'help' to get more ...

Evolution from IE8 to IE11

Here is the code snippet I am currently using: container = document.getElementById("menuContainer"); Following this, I have the following lines of code: container.document.open("text/html"); container.document.writeln(content); container.doc ...

Filter out the selection choice that begins with 'aa' in the drop-down menu

Here is a select field with various options: <select id="sel"> <option value="1">aadkdo</option> <option value="2">sdsdf</option> <option value="3">aasdfsddkdo</option> <option value="4"> ...

The JSON schema is failing to validate properly

I am having issues with my JSON schema validation. It seems to only recognize the first pattern. { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "Pr ...

There is a lack of a play.api.libs.json.Format instance for models.AccountStatus within the implicit scope

The implicit scope does not have any instance of play.api.libs.json.Format available for the model AccountStatus. The following code snippet is sourced from a GitHub page, with only class and variable names altered. package models import slick.jdbc.H2Pr ...

Guide on Generating Dynamic JSON to Set and Retrieve Values for Forms and Displaying the Bound Values

I'm a beginner in Ionic 3 and I'm having trouble creating a page that redirects to another page without validation. I want to display the data on the new page, but it's not working. Please help! I also want to create a dynamic JSON object a ...

WTForms can only submit the initial form

My blog page allows users to add their replies, which is working correctly. However, I am facing an issue with the edit feature - only the first form is submitting properly. For example, when I try to submit the second or third form, it always submits the ...

Change the date string to year, month, and day

When using Ajax's getResponseHeader("Last-Modified"), it returns a date string with the format displayed below: Thu Oct 13 2016 13:05:17 GMT+0200 (Paris, Madrid, sommartid) I am wondering if it is achievable in javascript to extract the year, month, ...

Transforming JSON or dictionary data into a flattened string format using special marker symbols

Consider the following input: {'example_id': 0, 'query': ' revent 80 cfm', 'query_id': 0, 'product_id': 'B000MOO21W', 'product_locale': 'us', 'esci_label': &apos ...

DataFrame conversion from JSON file resulted in a ValueError: Encountered an unexpected character while decoding an array value (2)

I am dealing with a large JSON file that follows this structure: [{"faceId": "2cb5a26a-1acc-4eb2-8c39-8e05e604f057", "faceRectangle": {"top": 54, "left": 125, "width": 78, "height": 78}, "faceAttributes": {"smile": 0.584, "headPose": {"pitch": 0.0, "rol ...

What is the method to deactivate all events in React components using refs?

Currently, I am utilizing TreeView from Material-ui along with a text field for searching other items on the screen. Although TreeView and TextField are unrelated components. However, I have encountered an issue where if I click on a TreeView node and the ...

Display the JQuery element that contains a child element with a specified class

On my webpage, I have a dropdown menu (ul) and I want to keep it open when the user is on the page. Specifically, I only want to display the ul item if it contains an li element with the class ".current-menu-item". The code snippet below accomplishes this ...

Converting JSON to CSV using Angular

I need help converting a JSON object into CSV format using Angular. I found this npm package at https://www.npmjs.com/package/jsonexport that looks promising, but I'm not sure if it's compatible with Angular (seems to be node specific). Are there ...

How to Fetch a Singular Value from a Service in Angular 4 Using a Defined Pattern

I am currently working on developing a service in Angular 4 (supported by a C# RESTful API) that will facilitate the storage and retrieval of web-application wide settings. Essentially, it's like a system for key-value pair lookups for all common appl ...

The rule result is invalid due to the occurrence of the Function()

As I proceed with the upgrade from angular 6 to angular 7, I am diligently following the guidelines provided on the official Angular website. Upon executing the command to update angular/cli and core for version 7: $ ng update @angular/cli@v7 @angular/c ...

When using node.js and express, attempting to send an email with the packages 'nodemailer' and 'nodemailer-handlebars' may result in a TypeError being thrown, specifically [ERR_INVALID_ARG_TYPE]

I am encountering an issue while attempting to send an email using an HTML template located in the 'view' folder within the same path. The HTML template is named 'index.handlebars'. Despite believing that the path is correct, I am recei ...

Having trouble establishing a database connection through JSON

I recently developed a Database-oriented app using MySQL. The app connects to the database through a JSON PHP file, but I am facing a challenge in implementing multiple user functionality with different usernames and passwords. Although I found some examp ...

What are the different kinds of properties that can be used in Vue.js

When working with Javascript, I can create arrays that hold different types of data elements like: var ex = ['name', 12, true]; console.log(ex); In Vue JS, when defining props for a component within a single file template, I have the option to ...