Creating a JSON property value in real-time

JSON object structure:

{
    "critiquesAvg": 4.75: , 
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 4.5
        }
    ]
}

I am seeking assistance in dynamically calculating the value of critiquesAvg by averaging the stars property from the critiques array.

EDIT: Upon further examination, I encountered a different challenge:

var dealers = [{
    "id", 1874
    "critiquesAvg": 4.75 ,
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 4.5
        }
    ]
},
{
    "id": 1345,
    "critiquesAvg": 5 ,
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 5
        }
    ]
}
];

In this scenario, I require assistance in dynamically computing the values of the critiquesAvg property based on the average critiques for each dealer's data entry.

Answer №1

To tackle this problem, I recommend using the reduce function (view code snippet here):

var data = {
    "critiquesAvg": 4.75, 
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 4.5
        }
    ]
};

var sum = data.critiques.reduce(function(x, y) { return x.stars + y.stars });
var average = sum / data.critiques.length;

data.critiquesAvg = average;

To address the revised question, you should incorporate an additional loop, possibly utilizing forEach (updated fiddle here):

dealers.forEach(function(data) {
    var sum = data.critiques.reduce(function(x, y) { return x.stars + y.stars });
    var average = sum / data.critiques.length;

    data.critiquesAvg = average;
});

Answer №2

To achieve this, you can swap out critiquesAvg with a custom function:

calculateAverageRating: function(){
    var totalStars = 0;
    for(i=0;i<this.ratings.length;i++) {
        totalStars += this.ratings[i].stars;
    }
    return totalStars / this.ratings.length;
}, 

For more details, refer to the script.js in this Plunker: http://plnkr.co/edit/zAbCdEfGhIjKlMnPqR?s=preview

Answer №3

Ensure to add an init function to your object, where all calculations are performed. In many object-oriented languages, these calculations are typically done in the constructor. Similarly, you can achieve similar functionality with a custom method acting as a constructor to set up the initial state of your object.

var obj = ({
  "critiquesAvg": 0, 
  "critiques": [{
    'author': 'John Does',
    'comment': "I like it",
    'stars': 5
  }, {
    'author': 'Jacob Works',
    'comment': "I like it too",
    'stars': 4.5
  }],
  init: function() {
    var result = this.critiques.reduce(function(prev, current, idx, arr) {
      return prev['stars'] + current['stars'];
    });
    this.critiquesAvg = result / this.critiques.length;
    return this;
  }
}).init(); // invoking the init method inline here (coding pattern)

This coding pattern is often used to set object states, especially when using object literal syntax in JavaScript.

DEMO

Updated answer

Follows a similar pattern, but instead of having an init method for each object, a common initialize method performs the same operation.

var initialize = function() {
  var result = this.critiques.reduce(function(prev, current, idx, arr) {
    return prev['stars'] + current['stars'];
  });
  this.critiquesAvg = result / this.critiques.length;
  return this;
};

var dealers = [({
  "id": 1874,
  "critiquesAvg": 0,
  "critiques": [{
    'author': 'John Does',
    'comment': "I like it",
    'stars': 5
  }, {
    'author': 'Jacob Works',
    'comment': "I like it too",
    'stars': 4.5
  }],
  init: initialize
}).init(), ({
  "id": 1345,
  "critiquesAvg": 0,
  "critiques": [{
    'author': 'John Does',
    'comment': "I like it",
    'stars': 5
  }, {
    'author': 'Jacob Works',
    'comment': "I like it too",
    'stars': 5
  }],
  init: initialize
}).init()];

DEMO

Answer №4

It was Robby who initially did it, but I decided to turn it into a function

function processData(data){
    //to avoid global data overwrite as objects are references
    var newData = data;
    var total = newData.critiques.reduce(function(x, y) {
        return x.stars + y.stars 
    });
    var averageRating = total / newData.critiques.length;

    newData.critiquesAvg = averageRating;
    return newData;
}

var initialData = { 
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 4.5
        }
    ]
};

initialData.critiques.push({
    'author': 'Wacob Works',
    'comment': "I like it too",
    'stars' : 3.5
});

initialData = processData(initialData);

Great! The update aligns with your needs, hope this solution helps http://jsbin.com/sevor/1/edit

var dealers = [{
  "id": 1874,
    "critiquesAvg": 0 ,
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 4.5
        }
    ]
},
{
    "id": 1345,
    "critiquesAvg": 5 ,
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 5
        }
    ]
}
];

var Dealers = {
    calculateAverage: function(dealer){
        var sum = dealer.critiques.reduce(function(x, y) {
            return x.stars + y.stars; 
        });
        var average = sum / dealer.critiques.length;
        return average;
    },
    generateAverages: function(allDealers){
        for(i=0;i<dealers.length;i++){
            dealers[i].critiquesAvg = this.calculateAverage(dealers[i]);
        }

        return allDealers;
    }
};

dealers = Dealers.generateAverages(dealers);

dealers.push({
    "id": 1346,
    "critiquesAvg": 0 ,
    "critiques":[
        {
            'author': 'John Does',
            'comment': "I like it",
            'stars' : 5
        },
        {
            'author': 'Jacob Works',
            'comment': "I like it too",
            'stars' : 5
        }
    ]
});

dealers = Dealers.generateAverages(dealers);
console.log(dealers);

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

Sending an array object from Ajax to Django Framework

AJAX Script Explanation: Let's consider the variable arry1D contains values [0,1,2,3,4] $.ajax({ url: "{% url 'form_post' %}", type: "POST", data: { arry1D: arry1D, 'csrfmiddlewaretoken': tk }, ...

Creating a customizable React application with an extra environmental setting

I'm currently working on an app that requires some variations. While the core remains the same, I need to customize certain parts of the app such as color schemes and images. My inquiry is: Is it feasible to construct an app with a specified instance ...

iPhone users experiencing issue with Bootstrap Modal failing to open

My website utilizes a BS Modal that successfully opens on laptops and mobile simulators such as Safari Responsive Design Mode. However, when accessed from a physical mobile device (iOS 11 iPhone X), the modal fails to open. Check out the page ...

What is the reason for the automatic loading of coffee files in app/assets/javascripts across all files?

I have a question about organizing my Javascript files in my app. I have multiple files in the app/assets/javascripts folder, and for testing, I have written some code in a file named test.coffee: $ -> $(document).ready -> alert("Hey"); When ...

VueJS: Connecting data to Components

I'm struggling to articulate this question clearly, and the documentation isn't providing the answers I need. Essentially, in my dataset, I have an array with two values that represent the day of the week index. I want to create a custom range c ...

Troubleshooting a ThreeJS Issue: the Mystery of the Malfunction

I have a ribbon showcasing various thumbnails. These thumbnails are painted on a canvas and then added to a Texture. var texture = new THREE.Texture(textureCanvas); The mesh is generated as shown below loader.load('mesh_blender.js', functi ...

The connection between the `http.request()` method, the `ClientRequest` variable, and the `callback

I am new to Node.js and currently exploring its API. After referencing some resources, I was able to write a crawler that successfully posts comments on a website. However, I am unsure about the execution order involving the return class - clientRequest an ...

Changes to the model cannot be realized unless $scope.$apply is used

Are there alternative methods to achieve the desired model change without utilizing $scope injection in an Angular "controller as" approach within the given setup? The HTML: <div data-ng-controller="Buildings as vm"> <select data-ng-model="vm. ...

Utilizing the Enter Key to Trigger an AJAX Function in jQuery

Recently, I came across a textbox in my HTML code: <input id="myInfo"> My goal is to trigger an AJAX function once the user inputs some value into the textbox using jQuery. The desired outcome is for the function to be executed immediately upon pre ...

What is the best way to send the value of a Select component from a child to a parent component in

Users have the ability to select a category, triggering the appearance of another dropdown menu based on their selection. I have created a separate component in a different file (.js) to handle this second dropdown. While I can see the data, I am wondering ...

Insert incoming comments into the comments array using mongoose/mongodb in conjunction with AngularJS

I've been facing a challenge for the past three days trying to insert a new comment object into my array of comments using a Yo generated CRUD module. Below is the server.model for my comments schema, utilized as a subdocument: var CommentsSchema = ...

Leveraging PHP cURL for sending data via the POST method to the /oauth2/access_token endpoint and retrieving data in JSON

Following the steps mentioned in the Path API tutorial on User Authentication, users are directed to a specific URL where they are prompted to grant access: Upon completing this step, the server responds with an authorization code, as explained in the doc ...

Turn off automatic reloading in Vite for ReactJS

When using my application, I encounter a significant issue with vite's automatic page reload functionality. This causes the extensive loading for certain functions to restart, resulting in lost progress on the page. I am looking for a solution to disa ...

Is there a more efficient method to construct my array without individually defining each key or element?

Dealing with a function that compiles data from multiple tables into an array for a calendar/agenda. The challenge lies in the method growing larger and more complex as new items are added to the calendar. Despite some refactoring efforts, it remains a cum ...

How can the type of array elements be specified in an NSDictionary with values NSArray when using MOTIS Object Mapping?

My JSON data is structured as follows: {"Types":{ "food":[{"cve":"1","description":"Pizza"},{"cve":"2","description":"Restaurant"},{"cve":"3","description":"Cafe"}], "Health":[{"cve":"3","description":"Pharmacy"},{"cve":"4","description":"Hospit ...

Tips for saving JSON data in a file with writeFileSync

I'm currently working on a project related to home automation using IoT technology. In this project, my websocket server acts as a subscriber to a MQTT broker, receiving temperature and light intensity data from a microcontroller in the form of JSON d ...

What is the reason that I have to submit my mapped function twice in order for the updated state to show after modifying the array content?

When I try to display an image for the current value in the array item, the image does not display when I submit my value. I have to submit twice to display the value. Additionally, when changing the value and pressing submit, the content in the div does ...

Unexpected Issues with Two-Way Binding in AngularJS Using ng-repeat

Currently, I am utilizing AngularJS within a Firebase application and have implemented a function that involves some inner join operations to retrieve data. Further information can be found here. Upon receiving the response from the Firebase API, I constru ...

An issue has been encountered with the Vue Router within the Micro Front End/Web Components setup, displaying the error message: "Uncaught TypeError:

I encountered an issue that I need help with. Here is the scenario: I have built a Vue application called my-admin micro app consisting of 4-5 screens/components (manage user, manage notifications, manage roles, etc.). I created a router.js file where I d ...

When the NPM package is imported as a whole, it shows up as undefined. However, when it

I've come across a peculiar issue in my code where importing the textile/hub package in Node.js and then destructuring it later results in an error. However, if I destructure it while importing, the program runs without any issues. Can anyone shed som ...