Opt for Object.keys() over .length when dealing with Firebase Objects

How can I update this snippet to use Object.keys()? It currently works well when the comment ids are numbers, but how can it be adapted to work with auto-generated ids from Firebase?

(The data structure is provided below)


ngOnInit() {
  this.route.params     
    .pipe(switchMap((params: Params) => this.dishservice.getDish(params['id'])))
      .subscribe(dish => {
        this.dish = dish;
        this.favorite = this.favoriteService.isFavorite(this.dish.id); 
          
        // Calculate the average of ratings and display the number of comments
        this.numcomments =  this.dish.comments.length;           
        let total = 0; 
        this.dish.comments.forEach(comment => total += comment.rating); 
        this.avgstars = (total / this.numcomments).toFixed(2); 
      },
      errmess => this.errMess = errmess); 
}

https://i.sstatic.net/gKsxv.jpg

Answer №1

Give this a shot

const commentIds  = Object.keys(this.dish.comments);
this.numcomments =  commentIds.length;           
let total = 0; 
commentIds.forEach(commentId => total += this.dish.comments[commentId].rating); 
this.avgstars = (total/this.numcomments).toFixed(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

Extract objects from a nested array using a specific identifier

In order to obtain data from a nested array of objects using a specific ID, I am facing challenges. My goal is to retrieve this data so that I can utilize it in Angular Gridster 2. Although I have attempted using array.filter, I have struggled to achieve t ...

$wpdb originating from a separate WordPress database

My challenge involves retrieving the database prefix from a separate WordPress database. In my current WordPress database, I utilize the following code: $db_prefix = $wpdb->base_prefix; Now, my objective is to obtain the database prefix from an extern ...

Tips for organizing an array into three separate objects based on specific criteria

I have taken a word and split it into an array. Now, I am trying to divide that array into 3 separate objects like this: Input: var input = "7RD FLOOR, PAVE AVENUE BUILDING, DUNG STREET, 48 JUNG-GU, SEOUL 100-203" Desired Output: let addresses = { ad ...

Encountering a hitch while attempting to integrate a framework in Angular JS 1

Having experience with Angular JS 1 in my projects, I have always found it to work well. However, I recently encountered a project that uses Python and Django, with some pages incorporating Angular. The specific page I needed to work on did not have any An ...

Express displaying undefined when referring to EJS variable

After receiving valuable assistance from user Jobsamuel, I have been encountering challenges in displaying the data retrieved from an API call on a webpage: // EJS template to show API data. app.get('/activities', function (req, res) { if (re ...

Update the ng-model in AngularJS when the value is set to true

Hello there, I am in the process of developing an app that provides a summary of data from a database. In this app, there is a form that populates input fields with information using ng-model. Users can edit these values as needed. However, I want to ensu ...

Getting rid of background color in a tooltip using Material UI

I'm currently tackling an issue with Material UI's tooltip. I can't seem to find a way to make the background of the tooltip completely transparent. By default, it displays with a grey background and white text. Changing the background color ...

Utilize React's useState hook in combination with TypeScript to effectively set a typed nested object

In my project, I have a burger menu component that will receive two props: 1) isOpen, and 2) a file object { name, type, size, modifiedAt, downloadUrl } I'm attempting to implement the following code snippet, but I am encountering issues with Typescr ...

Retrieve characteristics from removed or replicated entities and allocate them to different entities

Looking for a bit of assistance with an array transformation: [ {Code:13938, Country:699, Name:"Crocs", codeProduct:1} {Code:13952, Country:699, Name:"Polo Club", codeProduct:14} {Code:13952, Country:699, Name:"Polo Club", codeProduct:1} {Code ...

What is the process for importing files in a Firefox extension (add-on)?

We have developed browser extensions for Chrome, Firefox, and Safari. The Firefox extension includes a tracker called tracker.js, which is accessed from the controller using this line of code: tracker = require("../../firefox/tracker.js").tracker; The tr ...

Issue with index creation using the @index decorator in Typegoose with NestJS and MongoDB

Encountering an issue with typegoose. Trying to create a 2dsphere index on the property geoLocation of model SP. Utilized the typegoose decorator @index but it's not functioning and not throwing any errors. Uncertain about how typegoose handles this s ...

Converting line breaks into a visible string format within Angular

After thorough research, all I've come across are solutions that demonstrate how to display the newline character as a new line. I specifically aim to exhibit the "\n" as a string within an Angular view. It appears that Angular disrega ...

Removing elements from an array in JavaScript using subtraction

I have 2 arrays structured like this : VM.dataTotalList = result.map(item => { return { idEquipment : item['0'], timestamp : item['1'], value ...

Preventing opening while closed through the OnClick event

I have the following OnClick function: const [open, setOpen] = useState(true); and onClick={() => setOpen(!open != true)} The goal is to "close when open" and "remain closed if already closed". The current code achieves the second part but not the fir ...

"Efficiently managing multiple selections in Angular ui-select with a pristine ng

While attempting to utilize the ui-select feature, I have encountered an issue where the component is clearing my array. For example: {{ vm.staff_hotels }} <ui-select multiple ng-model="x" theme="bootstrap"> <ui-select-match placeholder="Not ...

Here is a method to transform the JSON object into a string as demonstrated below:

Presented below is a JSON object: { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } } I am looking t ...

Ways to dynamically link a JSON response object to an entity?

In my ng2 implementation, I have a user.service.ts file that calls a REST service and returns JSON data. The code snippet below shows how the getUser function retrieves the user information: getUser(id: number): Promise<User> { return this.http. ...

What is the process for triggering an exception?

I have a specific function that converts a two-dimensional array into CSV format. The key requirement is that the function only supports text and numbers, triggering an error message for any other input types. Currently, when I execute the function, it s ...

If there is only one item, jCarousel will not display anything

After incorporating jCarousel into jQuery ui Tabs, I created a page which can be found at the following link: The issue arises when clicking on the 3rd tab (containing only one item), as nothing is visible until the left arrow is clicked to navigate back. ...

Having trouble with Node integration in Electron?

In my inventory application, I have the backend written in Python 3.7 and I am using Electron to create a GUI for it. To communicate with the Python code, I am utilizing the Node.js Module "python-shell" and would like to keep all of its code in a separate ...