Guide to organizing an object containing a named list of objects by a specific field in Typescript

I've been working with data in JavaScript, and so far I've been able to do everything I needed on my own. However, I've hit a roadblock.

Explaining the structure of my data is tricky, so let's create a schema for it. Here's what I have:

    obj: {[key: string]: {name: string, type: string}[]} = 
    {
        "animals": [
          {name: "Louis", type: "dog"},
          {name: "John", type: "cat"},
          {name: "Jordan", type: "dog"}
        ],
        "cars" : [
          {name: "alpha", type: "ferrari"},
          {name: "beta", type: "ferrari"},
          {name: "charlie", type: "mercedes"}
        ]
     }

My goal is to group each object by type within the list. It should look like this:

obj: {[key: string]: {[key: string]: {name: string, type: string}[]}} = 
{
    "animals": {
      "dog": [
          {name: "Louis", type: "dog"},
          {name: "Jordan", type: "dog"}
      ],
      "cat": [
          {name: "John", type: "cat"}
      ]
    },
    "cars" : {
      "ferrari": [
          {name: "alpha", type: "ferrari"},
          {name: "beta", type: "ferrari"}
      ],
      "mercedes": [
          {name: "charlie", type: "mercedes"}   
      ]
    }
}

Any suggestions on how to accomplish this?

Answer №1

For those seeking a solution related to TypeScript, the code snippet below might be what you need:

interface Data {
  name: string;
  type: string;
}

type GroupedData = {
  [index: string]: Record<string, Data[]>;
};

const organizedResults = Object.entries(object).reduce<GroupedData>((accumulator, [key, values]) => {
  const grouped: Record<string, Data[]> = {};

  for (const val of values) {
    if (grouped[val.type] === undefined) {
      grouped[val.type] = [val];
    } else {
      grouped[val.type].push(val);
    }
  }

  return {
    ...accumulator,
    [key]: grouped,
  };
}, {});

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

Encountering TypeScript error in the beforeRouteUpdate hook with Vue and vue-property-decorator

I am developing an application using Vue 2 with TypeScript and vue-property-decorator. Within my component, I am utilizing the beforeRouteEnter/beforeRouteUpdate hooks. One of the methods in my component is findProjects, which I want to call within the bef ...

"Troubleshooting: Text Added to Element in JavaScript Not Appearing

I am in the process of developing an online task list for users, and I want it to work in such a way that when a user enters a task and clicks the 'JotIT' button, the task is added to the list. Currently, the function to add tasks is working, bu ...

Show a jQuery box when hovering and disappear when the mouse leaves

I'm currently working on creating a box that pops out when a link is hovered over. Although I have the basics covered, I've been struggling to fully achieve my desired outcome. You can view my progress here: http://jsfiddle.net/EpV87/1/ (please ...

Modify the label contents to reflect the selected file, rather than using the default text

Currently, I am working on customizing my file upload input to enhance its appearance. Everything is going smoothly so far, but I am facing difficulty in finding a suitable jQuery script that can meet my specific requirements. My objective is to have the ...

The JavaScript file failed to load

My HTML code is having trouble loading all the files. The Javascript files UserController.js and RepoController.js are not being loaded, which means they are not displayed in the developer tools source tab. When I press F5 in the network tab, the files are ...

Using React to iterate through the child components of the parent

I have created a component that can accept either a single child or multiple children. Here is an example with multiple children: <SideDataGridItem> <div id='top'> <div>A1</div> <div>B1</div> ...

Invalid JSON Error in C# with JSON

I am currently working on constructing a JSon string using the following code snippet: push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(RegID) .WithJson(@"{""message"":"+Message+"}")); However, every tim ...

Here is a new version: "AJAX button enables updating a single row in SQLite database through PHP."

My webpage features a table that shows values entered by a user, along with two buttons for removal and completion. The table is part of a layout with three tabs named Tab1, Tab2, and Tab3. Each tab contains its own table displaying information related to ...

What is the best way to integrate Vuex store within the router of a Vue 3 SSR application?

Currently, I am working on a Vue3 project with SSR, Vue-Cli, Vuex, and Typescript. While trying to commit data to the Vuex Store from the router page, I faced an issue. In a .vue file, it's straightforward as I can use this.$store with the typings in ...

Setting the default value for ngModel does not receive any information from the model

I am trying to populate a form with default values using the code below: <h3>ِStart Time</h3> <div class="row" > <div class="col"> <label for="startTime">Hour(s) </label> <input type="numb ...

Guidelines on extracting information from a POST request, evaluating it based on a specified criteria, and providing a corresponding feedback

I'm on the hunt for a simple solution to facilitate communication between the front-end and back-end. What I envision is creating a basic JavaScript front-end client where a user can enter a number between 1 and 10,000 to guess a random number genera ...

Tracking File Upload Progress with PHP and Ajax

<form enctype="multipart/form-data" action="upload.php" method="POST"> <input name="uploaded" type="file" /> <input type="submit" value="Upload" /> </form> <?php if(isset($_REQUEST['submit'])){ $target = "files/".ba ...

Logging in Angular can be accomplished using "console.log"

I am experiencing an issue where I cannot see any console logs and I'm unsure if the cookie is being entered into my controller from the HTML page. var addPartyApp = angular.module('addPartyApp',['ngCookies']); addPartyApp.co ...

Issues with Drupal's $get function have been preventing the retrieval of complete

I've created a custom Drupal module where I'm trying to call the .module file using $get. It's functioning correctly, but it's returning the entire HTML page. I attempted to use drupal_json_output since I am working on Drupal 7. I also ...

Unable to transmit data to CodeIgniter controller through ajax communication

I'm struggling with sending a value from an input element to a Codeigniter controller using ajax. The problem arises because I am using a WYSIWYG editor (summernote), which only allows me to receive the input inside a <script>. However, when I ...

Ensure that the number is valid using Express Validator in Node.js

One thing that I've noticed when using express validator is the difference between these two code snippets: check('isActive', 'isActive should be either 0 or 1').optional({ checkFalsy : false, nullable : false }).isInt().isIn([0, 1 ...

Struggling to add a line break in my code

class Test extends React.Component{ state={name: "John", numTimes: 2}; render() { let output = "" for (let i = 1; i <= this.state.numTimes; i++) { let evenOdd = i % 2 if (evenOdd === 0) { output += i + ". Hello " + this.state.name + ...

Incorporating the Three.js EffectComposer into your 8th Wall project

I'm attempting to implement a three.js postprocessing bloom effect with 8th Wall, but I'm encountering difficulties getting it to work correctly. In head.html, I'm including the EffectComposer by using: <script src="http://mrdoob.gi ...

SlidingPane header in React disappearing behind Nav bar

Here is the code snippet from my App.js file: export class App extends React.Component { render() { return ( <BrowserRouter> <NavigationBar /> <Routes /> </BrowserRout ...

Utilizing AJAX and PHP POST to dynamically refresh innerHTML content with MySQL data updates

I've been trying to solve this problem for a long time now, and I've reached a point where I can't seem to figure it out. On a page, there are several forms where users input different information that gets submitted to a mySQL database usin ...