JavaScript - Organizing Objects

I have successfully implemented a code to group objects by their category. Here is the code snippet:

  let groupBy = (element, key) => {
    return element.reduce((value, x) => {
          (value[x[key]] = value[x[key]] || []).push(x);
       return value;
     }, {});
   }; 
  let items = groupBy(results, 'category')

The resulting grouped objects look like this:

{
    "Administration": [
        {
            "shp_name": "Village Boundary",
            "color_prop": "#000000",
            "shp_prop": "Batu Ampar"
        },
        {
            "shp_name": "Village Boundary",
            "color_prop": "#FFFFFF",
            "shp_prop": "Sungai Jawi"
        }
    ],
    "Land_use": [
        {
            "shp_name": "Land Use 2019",
            "color_prop": "#000000",
            "shp_prop": "Grassland"
        },
   ]
}

Now, I need help in merging the color_prop and shp_prop into arrays within each object. The desired output should be like this:

{
    "Administration": [
        {
            "shp_name": "Village Boundary",
            "color_prop": ["#000000","#FFFFFF"],
            "shp_prop": ["Batu Ampar","Sungai Jawi"]
        },
    ],
    "Land_use": [
        {
            "shp_name": "Land Use 2019",
            "color_prop": ["#000000"],
            "shp_prop": ["Grassland"]
        },
    ]
 }

If anyone could assist me with this issue, I would greatly appreciate it. Thank you.

Answer №1

One possible solution is to create a function that can transform "rows" into "columns".

function convertToColumns(rows) {
  const columns = {};
  const keys = Object.keys(rows[0]);
  for (const key of keys) columns[key] = [];
  for (const row of rows) {
    for (const key of keys) {
      columns[key].push(row[key]);
    }
  }
  return columns;
}

This function works on data structured like this:

[
  { a: 1, b: 2 },
  { a: 3, b: 4 },
]

The output will be:

{ a: [1, 3], b: [2, 4] }

By using this function, you can transform your groups into the desired format as shown below:

for (const category in items) {
  const columns = convertToColumns(items[category]);
  // replace 'shp_name' with its first value instead of an array
  columns.shp_name = columns.shp_name[0];
  items[category] = columns;
}

In case you want to keep the original object intact, change items[category] = columns to result[category] = columns (where result is defined as const result = {} before starting the loop).

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

navigate to a different section on the page with a series of visuals preceding it

When I try to navigate to a specific dom element on another page, the page initially works fine but then jumps to somewhere before that element. I believe this issue occurs because the page calculates the position before images load, and once the images ar ...

Is it possible to generate distance between 2 elements without utilizing padding or margin?

In my React Native project, I'm currently working with 2 inline buttons - the search and add buttons: https://i.stack.imgur.com/tKZrf.png I'm looking to add some spacing between these buttons without impacting their alignment with the left and ...

Get an ICS file as text using JQuery

As a newcomer to JQuery and JS, I seek your understanding for any mistakes I may make. My current goal is to extract the text from an ICS file (e.g. BEGIN:CALENDAR....) using JavaScript. Here is a simple HTML file I am working with: <html> <b ...

Retrieve relationship data from tables as JSON format, where there is a one-to-many connection

These two tables are derived from the diagrams. Each question may have multiple answers. I am looking to retrieve data by question ID in JSON format, similar to the structure below: var initialData = [ {question_id: "1", Description: "Danny", Status: ...

Ways to retrieve numerous values from an array

I'm currently working on an assignment that is due in a few days, and I've hit a roadblock with one of the functions. The task at hand is to extract data from an array and display 10-20 database entries from the array. This is the function I hav ...

Tips for highlighting text in a textarea using jQuery or JavaScript

I'm intrigued by Facebook's functionality. They utilize textareas in their comments and status sections, but whenever I tag someone in a post, the selected text is highlighted with a light blue background within the textarea. As far as I know, th ...

Issue with saving cookie from Express.js backend to Nuxt.js frontend

After successfully creating an authorization server using Express.js, I encountered a problem when trying to save the access and rotating refresh tokens as signed cookies. The issue arose from having separate backend and frontend servers with different dom ...

What is the best way to send information from child components to their parent in React

I'm facing a scenario where I need to increase the parent value based on actions taken in the children components. Parent Component: getInitialState :function(){ return {counter:0} }, render(){ <CallChild value={this.state.counter}/> ...

Error: Unable to access attachShadow property as it is null and cannot be read

Having an issue with my vue component where I am getting a TypeError: Cannot read properties of null (reading 'attachShadow') error when building it as a web component. Here is the command I am using to build the vue component: vue-cli-service bu ...

How can we include identical item names within a single JavaScript object?

My attempt at achieving the desired result involves creating an object like this: var obj = {id: id, items: "asdf", items: "sdff", test: varTest}; However, I face a challenge where I need to dynamically add two elements with the same name 'items&apo ...

JavaScript - Two tables shown in parallel

Beginner coder seeking assistance! I am currently working on an application with two user input fields placed adjacent to each other. Clicking parse buttons next to these fields generates two separate tables. However, I need these tables to be displayed si ...

Arrange the array based on the order of the enumeration rather than its values

Looking to create an Array of objects with enum properties. export enum MyEnum { FIXTERM1W = 'FIXTERM_1W', FIXTERM2W = 'FIXTERM_2W', FIXTERM1M = 'FIXTERM_1M', FIXTERM2M = 'FIXTERM_2M', FIXTERM3M = 'FIX ...

Vue.js video player component displays at a width of 100 pixels

I recently started implementing the vue-video-player library into my project. However, I'm facing an issue where the player renders at a width of only 100px. I'm not sure why this is happening or how to adjust it. After going through the documen ...

What is the most effective method for comparing and updating objects within arrays or lists in frontend Angular applications using TypeScript?

While I acknowledge that this approach may be effective, I am of the opinion that there exists a superior method to accomplish the same goal I have two separate lists/arrays containing distinct objects, each with a common attribute. My objective is to ite ...

Is there a syntax error in Javascript when using a string and variable with the GET method?

Is there a way to send a value using the get method? In JavaScript, we need to use the + symbol to concatenate strings. But my issue goes beyond this simple problem. If I attempt the following: Let's say; var sID = 16; var rID = 17; EDIT-2: I act ...

Tips for testing and generating test scenarios for AngularJS within the Eclipse environment

In the process of building a Maven project, I have incorporated Angular JavaScript for client-side scripting. I am now looking to test my JavaScript code in Eclipse, but I am struggling to figure out how to do so. I attempted using Karma, but unfortunatel ...

Flask causing AJAX Request to encounter a CORS Policy issue

Currently, I am utilizing Flask to construct a basic backoffice system. In an attempt to execute some requests on the client-side using AJAX, I keep encountering a persistent error: Access to XMLHttpRequest at '...' from origin 'http://lo ...

Nested ListView configuration

I created a custom list view to populate my screen with posts. Some of the posts include comments, which is why I need another list view to display the comments along with the post. Using Volley, I have implemented a Post class with getter and setter metho ...

Selecting DigitalOcean city based on user location in Node.js

Currently, I am implementing Node.js in conjunction with my HTTP server. My goal is to have every user who connects to the server be linked to a real-time game server through WebSockets. Furthermore, I aim for users to automatically connect to the nearest ...

Detect if a value is a member of an array in Swift

I am currently working with an array of type "User" in my code and I need a way to check if a specific value belongs to a property within the array. Here is a snippet of my code : struct User: Identifiable { var id = UUID() var ...