I'm looking to transform this array into the format described below, and also include another nested subarray within it using TypeScript

[{
     "header": "API",
     "value": "hello"
  },
  {
     "header":"API",
     "value":"yellow"
 },
   {
     "header":"Other",
      "value":"yallow"},
    {
      "header":"other",
      "value":"othertt"
     }

   ]

I have a list of objects with headers and values, and I want to restructure it so that all values with the same header are grouped together under one object. The output I'm aiming for is to have each unique header along with an array of corresponding values. Here's what I want to achieve from the initial list in TypeScript:

 [
   {
     "header": "API",
     "data": [
     {
         "value": "hello"
     },
     { 
         "value": "yellow"
      }
     ]

   },

  {
    "header": "other",
    "data": [
    {
         "value": "yallow"
    },
   { 
         "value": "othertt"
   }


   ]}
  ]

Answer №1

I have successfully tested this code snippet in my Angular application:

const data = [{
      "category": "Food",
      "name": "Pizza"
    },
    {
      "category":"Food",
      "name":"Burger"
    },
    {
      "category":"Drink",
      "name":"Soda"
    },
    {
      "category":"Drink",
      "name":"Smoothie"
    }];
    
    const categories = [];

    for (let item of data) {
      if (!categories.includes(item.category)) categories.push(item.category);
    }

    const categorizedData = categories
      .map(c => Object.assign({ category: c }, { 
        items: data.filter(x => x.category === c)
        .map(y => Object.assign({}, { name: y.name })) 
      }));

    console.log(JSON.stringify(categorizedData, null, 2))

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

How can you make a checkbox function like a select in AngularJS?

Is it possible for AngularJS to automatically bind all values (options) when a user selects something from a list, populating them via the model? How could I achieve a similar functionality with checkboxes? I want a select for multiple values and a checkbo ...

Validating Angular UI without requiring an input field (validating an expression)

Currently, I am utilizing ui-validate utilities available at https://github.com/angular-ui/ui-validate The issue I am facing involves validating an expression on a form without an input field. To illustrate, consider the following object: $scope.item = ...

Is it possible for the angular $resource module to return data in a format other than JSON?

I am seeking to extract data from a website that offers an API for retrieval. However, I am unsure about the format of the data. Is it in JSON? Is it an array or an object? Could someone take a look and provide insights? Cheers! https://i.sstatic.net/xMSm ...

The outcome displays an array of System.String objects

When I visit my GetBusiness.aspx page, a test list is created List<string> l = new List<string>(); l.Add("one"); l.Add("two"); l.Add("three"); l.Add("four"); l.Add("five"); // B. ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

Having trouble getting access to FormArray content for validation due to receiving null or undefined errors

CSS Tricks <form [formGroup]="newMovieForm"> <ng-container formArrayName="actors"> <ng-container *ngFor="let actor of (actors['controls'] || []) ; let i = index"> <div [formGroupN ...

How can I retrieve a specific string from an Android JSON array?

I'm working with a Json script that fetches data from a Mysql database and displays it in various TextViews. I'm wondering how I can extract only the "idE" value and show it in the "TextViewTitulo" TextView. try { String response = "[{"0":"1","i ...

How to find a matching array in MongoDB collections

Is there a way to find documents in my MongoDB collection that have similar arrays and order them by their similarity value? For example: If I search for {chars:['a', 'b', 'c']} And the stored documents are: 1. {chars:[&ap ...

Troubleshooting $on in Angular

I have a situation where I need to pass a value from the Main controller to the Child controller. These are the two controllers involved: .controller('mainController', ['$scope', '$rootScope', '$location', 'CI ...

Removing an element from a session array

I need help removing an item from my array in a stored session. I've tried to do it, but instead of removing it, it seems to add more! Here's my code that displays the products in the cart with a remove button: foreach ($_SESSION['products ...

Loop through a list of names that all begin with the same letter

Having trouble understanding this concept. For instance: names = ["Steve", "Mason", "John", "Sarah"] If I want to display a message only for people whose names start with the letter "S" using the each method, how can I achieve this? pets = ["Scooby", " ...

Exploring the concept of data sharing in the latest version of Next.JS - Server

When using App Router in Next.JS 13 Server Components, the challenge arises of not being able to use context. What would be the most effective method for sharing data between various server components? I have a main layout.tsx along with several nested la ...

Utilize information from a broader range than the current range

Attempting to implement a text from a website into an iPhone application using a web scraper known as Osmosis. The data retrieval was successful, however, I am facing difficulty assigning the data to an array for usage outside of the function. Below is a s ...

How to Show Data from the nth Position in an Array Using a Velocity Template

When customizing email templates for app dynamics, we are required to utilize velocity template 1.7 I have a health rule called ab-cd-ef-gh. The first two parts remain constant while the last two parts represent the microservice name. I am interested in d ...

AngularJS consistently shows only one piece of data when used in conjunction with PHP

My AngularJS script below is currently only displaying one record at a time, replacing the previously submitted data. I would like it to display each submitted record individually. I suspect the issue may be related to the data call. I need it to show all ...

What could be the reason for receiving the error message "Function call failed: String is not a function"?

I'm facing an issue while trying to respond to messages in my inbox. I initially assumed it would be a straightforward process similar to sending a regular message. Instead of using $scope.messageTo and $scope.messageFrom, I mistakenly entered my emai ...

Make sure to always keep all stars contained within a div element

How can I keep five stars inside a div even when the screen size is small? I have created a div with an image and I want to place five stars within that div. However, as I reduce the size of the screen, the stars come out of the box. Is there a way to en ...

Can Material UI be defined as a peerDependency while maintaining its types as a DevDependency?

Is there a way to set Material UI as a peerDependency while keeping its types as DevDependency? I'm currently working on a component library using React + Typescript, with components based on Material UI and Rollup as the module bundler. For example ...

Utilizing Typescript version 1.5 alongside window.event.ctrlKey

When I need to debug, I occasionally check if the ctrl key is pressed for certain secret actions. This check may be included in any function, not necessarily an event handler itself (it could be a callback or an event handler). In my TypeScript code, I us ...

The reference to Angular is missing

My current file setup includes an index.html file and an app.javascript file. I keep encountering an error that says "Angular is not defined," even though my script files appear to be properly placed. Below are the contents of my index file and app.js file ...