How can I extract an array of objects from a response in Angular?

Arrange array of objects from the received data.

Here is the data that I received.

[ {name:someName, value:20},
  {name:"", value:21}
  {name:someName, value:25}
  {name:someName , value:27}
  {name:"", value:21}
  {name:someName, value:20}
]

I am looking to group it in the following way.

 [    {name:someName, value:20},
      {name:"", value:42}
      {name:someName, value:25}
      {name:someName , value:27}          
      {name:someName, value:20}
    ]

I attempted to achieve this using filter and reduce functions in JavaScript.

Answer №1

If you're looking to condense your code, you can use the reduce function like this:

const data = [ 
  {name: 'someName', value:20},
  {name: "", value:21},
  {name: 'someName1', value:25},
  {name: 'someName' , value:27},
  {name: "", value:21},
  {name: 'someName1', value:20},
];

const group = (data) =>

data.reduce((acc, { name, value }) => {

const item = acc.find((el) => el.name === name);

if (item) item.value += value;

else acc.push({ name, value });

return acc;
}, []);

console.log(group(data));

If you only want to group empty names find should be:

const item = acc.find((el) => el.name === name && !name);

Remember, empty strings are considered falsy values.

Answer №2

To streamline the process, convert the data to a Map and then utilize Array.prototype.map along with reduce method to aggregate the groups:

const data = [
  { name: 'a', value: 20 },
  { name: '', value: 21 },
  { name: 'a', value: 25 },
  { name: 'b', value: 27 },
  { name: '', value: 21 },
  { name: 'c', value: 20 },
];

console.log(
  [
    ...data
      .reduce(
        (result, item) =>
          result.set(
            item.name,
            (result.get(item.name) || []).concat(item),
          ),
        new Map(),
      )
      .values(),
  ].map((items) =>
    items.reduce(
      (result, item) =>
        console.log(result, item) || {
          name: item.name,
          value: item.value + result.value,
        },
    ),
  ),
);

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 Javascript array does not function like a typical array

I am currently facing a perplexing issue while working with the Twitter API. Below is the script causing the confusion: const Twitter = require('twitter-api-stream') const twitterCredentials = require('./credentials').twitter const t ...

Adjust the height of a div in JQuery to fit new content after specifying a height previously

I have a division element with an initial height of 0 and opacity set to zero, its overflow is hidden, and it contains some content. <div style='height: 0px; opacity: 0px; display: none; overflow: hidden; border: 1px solid #000;' id='myd ...

Intellisense for dispatch types in Redux Toolkit

After following the documentation for redux toolkit with typescript, I implemented my own useDispatch hook as shown below export const useAppDispatch = () => useDispatch<AppDispatch>() and used it in components like this const dispatch = useAppDi ...

Guide on how to bypass IDM when downloading a PDF file through a GET request

When I try to fetch a PDF by sending a GET request to the server and open it in a new tab, IDM interrupts my request and downloads the file instead. It changes the server response status to 204 and removes the headers. How can I prevent IDM from doing th ...

``Can someone provide guidance on how to showcase the validation check result for a text-field in the snackbar using Vuet

One of the challenges I'm facing in my project is implementing a validation function for the customer form. While using the vuetify validate method would be the easy way to go, I need to display the validation messages both as snackbar and next to eac ...

Encountered an error while attempting to install the @typescript-eslint/eslint-plugin

After starting the installation process for eslint plugins, I encountered an issue with @typescript-eslint/eslint-plugin. The plugin requires installation using--legacy-peer-deps, but this approach may introduce potential bugs by accepting an incorrect an ...

AFrame: keeping an element's world position and rotation intact while reparenting

I am attempting to reassign a child element (entity) to another parent while preserving its position, rotation, and possibly size in the scene. Ideally, I would like to implement a component (let's call it "reparent") that can be added to an entity to ...

What steps can be taken to resolve the mouse-pointer problem?

Currently, I am utilizing PHP, jQuery, JavaScript, and other tools for my website development. I have a new requirement for a script in jQuery/JavaScript that can trigger an alert when the user's mouse-pointer moves away from the tab where my website ...

Do server-side or client-side rendering render dynamic routes in Next.js?

I'm currently working on a project that necessitates server-side rendering for SEO benefits. I am utilizing Next.js and React, implementing Next.js dynamic routing for this purpose. To test if the setup is functioning correctly, I developed a basic p ...

The Datetimepicker component outputs the date in datetime format rather than a timestamp

Currently, I am utilizing the datetimepicker JavaScript script with specific implemented logic: <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth(); var yy = today.getF ...

What is the best way to transfer data from a database query to Vue?

I am currently working on an API request that involves calling a SQL query within the function. I want to pass the results to a .vue page utilizing express-vue. Below is the code snippet for the API request: router.get('/search', (req, res, next ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...

Troubleshooting dynamic route issues in Angular 6 when making changes in *ngFor

`<div *ngFor="let data of projects"> <a [routerLink]="'/projects/'+data.project_id"> {{data.project_name}}</a> </div>` When I click on the link, the URL changes from http://localhost:4200/projects/1 to http://localhost ...

Step-by-Step Guide: Crafting a Non-Ajax Popup Chat Application

Recently, I created a unique dating website with a one-to-one chat feature similar to Facebook. However, I implemented this using the ajax technique and the setInterval function in JavaScript for regular updates. Upon reflection, I believe that this appr ...

Printing Apex Oracle reports using Internet Explorer

I am facing a challenge with printing my page that contains two interactive reports. To enable printing, I have utilized a JavaScript function that triggers window.print(). I have incorporated CSS to adjust the layout of my tables when printed. @media pr ...

Swapping out data points using JQuery

What could be causing line 10 to return null? Click here for the code file The code seems to function properly with line 40, but not with line 10. ...

What is the best method for setting up message scheduling for a Microsoft Teams bot based on different time

I am trying to figure out how to send messages to users from my bot at specific time intervals. Currently, I'm using agenda for scheduling messages, but I've run into an issue with the timezone discrepancy - agenda is 5:30 hours behind my timezon ...

Disappearing Cloned Form Fields in jQuery

Hey there! I'm trying to duplicate a section of a form using the code below. But for some reason, the copied fields are only visible for a split-second before they disappear. Can anyone spot any errors that might be causing this strange behavior? jQu ...

Angular API snapshot error: The type 'IJobs' does not match the expected type 'IJobs[]'

Currently, I am in the process of learning and attempting to construct a job board using Angular 10. Although my API setup seems to be functioning properly, when navigating to the job detail page on Chrome, an error is displayed: ERROR in src/app/job-det ...

What is the process for validating multiple check boxes using the reactive forms module?

I thought this would be a simple task, but I'm having trouble figuring it out. There are three checkboxes and I need to ensure that the user selects only one. The validator should check if any of the other two checkboxes have been selected and preven ...