Calculating the frequency of a variable within a nested object in an Angular application

After assigning data fetched from an API to a variable called todayData, I noticed that there is a nested object named meals within it, which contains a property called name.

My goal is to determine the frequency of occurrences in the name property within the meals object. For instance, the meal Rice might appear multiple times in the data.

DATA

 [{"id":5,"referenceId":1189,"firstName":"Dan","lastName":"Daniels","orders":[{"id":109,"meals":[{"id":47,"name":"Fried Rice","description":"This is a  very sweet meal","image":"","mealType":"LUNCH","unitPrice":-20,"status":"ENABLED"}],"serveDate":"2019-07-11 00:00:00"}]}]

JS

let occurences = this.todayData.reduce(function (r, row) {
    r[row.orders.meals.name] = ++r[[row.orders.meals.name]] || 1;
    return r;
}, {});

let result = Object.keys(occurences).map(function (key) {
    return { meals: key, count: occurences[key] };
});
console.log(result);

Answer №1

SOLUTION:

r[row.orders[0].meals[0].name] = ++r[row.orders[0].meals[0].name] || 1;

It is necessary to set an index for properties that are of Array type.

EDIT 1:

This solution caters to data containing multiple orders and meals, offering a more general approach. (Credit goes to Bill Cheng for prompting me to consider this.)

let mealOccureneceCount = {};
  let occurences = this.todayData.forEach(user => {
    user.orders.forEach(order => {
      order.meals.forEach(meal => {
        mealOccureneceCount[meal.name] = (mealOccureneceCount[meal.name] || 0) + 1;
    });
  });
});
console.log(mealOccureneceCount);

Answer №2

let mealOccurrences = this.todayData.reduce((accumulator1, currentValue1) => currentValue1.orders.reduce((accumulator2,currentValue2) => currentValue2.meals.reduce((accumulator3,currentValue3) => { accumulator3[currentValue3.name]= (accumulator3[currentValue3.name] || 0) + 1; return accumulator3;}, accumulator2), accumulator1),{});

let resultArray = Object.entries(mealOccurrences).map(([key, value]) => ({ meals: key, count: value }));

console.log(resultArray);

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

What's up with the Chrome Dev Tools Error Log?

I am having an issue with debugging JavaScript files using breakpoints in Chrome Dev Tools. Whenever an error occurs, a red error message flashes on the screen so quickly that I can't read what it says. Is there a way to change this setting or access ...

Resetting Cross-Site Request Forgery (CSRF

Struggling to integrate Django's csrf with Angular 6? Check out this insightful thread I came across. It seems that Django changes the token on login, which makes sense as I can register and login using post requests but encounter issues posting after ...

Building a personalized django widget to enhance functionality on other websites

Currently, I am in the process of developing a new website that includes user statistics. My goal is to create a widget that can be embedded on other websites using JavaScript to pull data from my server and display the statistics for a specific user. Howe ...

Unreliable static URLs with Next.js static site generation

I've recently built a Next.js website with the following structure: - pages - articles - [slug].js - index.js - components - nav.js Within nav.js, I have set up routing for all links using next/link, including in pages/articles/[slug].j ...

What is the best way to keep an image fixed at the bottom, but only when it's out of view in the section

There are two buttons (images with anchors) on the page: "Download from Google Play" and "Download from App Store". The request is to have them stick to the bottom, but once the footer is reached they should return to their original position. Here are two ...

Scanning barcode and Qrcode with Angular js HTML5 for seamless integration

Looking to scan Barcode and Qrcode on Android, iPhone, and iPad devices for a project that is built on AngularJS and HTML5 as a mobile website. The requirement is not to download any third-party native application on the device, ruling out the use of nati ...

The AJAX callback resulted in the request being aborted and the window location being

I am currently working on implementing a client-side redirect for users who are deemed invalid. The server checks if the user has access to the current page, and if not, it returns {data: 'invalid'}. In the success callback of the ajax call, I va ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

Embedding a label's text directly as HTML code in an ASP.NET page

I attempted this CABC</td><td valign="top"><span class="progressBar pb3">document.getElementById('<%#Label8.ClientID%>').innerHTML</span></td></tr> I am trying to incorporate a jQuery script for a sales ...

Tips for updating form values with changing form control names

Here is an example of a form I created: public profileSettingsGroup = new FormGroup({ firstName: new FormControl('Jonathon', Validators.required) }) I also have a method that attempts to set control values in the form: setControlValue(contro ...

Tips for swapping out text with a hyperlink using JavaScript

I need to create hyperlinks for certain words in my posts. I found a code snippet that does this: document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href="www.ronaldo.com">Ronaldo</a>'); Whil ...

Creating a custom React hook in TypeScript to handle mouse events

I have been working on creating a custom hook in TypeScript/React, and I am looking to convert the code snippet below into a custom hook. Currently, I am passing handleClick to the onClick attribute in a div element to detect user clicks and route them to ...

Retrieve and manipulate the HTML content of a webpage that has been loaded into a

Hey, let's say I have a main.js file with the following code: $("#mirador").load("mirador.html"); This code loads the HTML content from mirador.html into index.html <div id="mirador"></div> I'm wondering if there is a way to chan ...

Issue with using bind(this) in ajax success function was encountered

In my development process, I utilize both react and jQuery. Below is a snippet of the code in question. Prior to mounting the react component, an ajax request is made to determine if the user is logged in. The intention is for the state to be set when a ...

The call to the Angular service has no matching overload between the two services in Typescript with 13 types

I encountered an error while creating a new Angular project following a tutorial, and I'm seeking assistance to understand it. The error message reads: "No overload matches this call. Overload 1 of 5... Type 'Object' is missing the followi ...

Press the button to modify the titles of the table

One of the tasks I'm working on involves a table with column titles. In this table, there's an edit button that, when clicked, should convert the title into an input field with the current title as its initial value. The edit button will then cha ...

Unable to locate the accurate information

Every time I run the cycle, there should be a match with the specified parameters and the message "OK" should appear. However, I am always getting a result of "No". request( { url: 'http://localhost:5000/positions/get', metho ...

Refreshing and enhancing Android contacts through the Expo project

For my current project, I am utilizing the Expo Contact module to automatically update contact information. Here is a part of my script that focuses on updating a selected phone number: const updateContact = async (callId, newCall) => { getSingleConta ...

Fetching data using an Ajax request in PHP is encountering issues, whereas the same request is successfully

I am experiencing an issue with a simple Ajax call in ASP.NET that works fine, but encounters a strange DOM Exception when I insert a breakpoint inside the onreadystatechange function. Can anyone explain why ASP.NET seems to have some additional header log ...

What is the purpose of having a constructor in Typescript when an interface is already used for a class?

Is it necessary to have a constructor in my class if the class already implements an interface? It seems like redundant code to me. interface PersonInterface { firstname: string; lastname: string; email: string; } class Person implements Pe ...