js - How to change one key's value based on another key's value in array of objects

后端 未结 4 995
眼角桃花
眼角桃花 2021-01-29 05:01

I have an array of objects like this:

var chartData = [{count: 0, idTag: \"24\"}
                 {count: 0, idTag: \"25\"}
                 {count: 0, idTag: \"         


        
相关标签:
4条回答
  • 2021-01-29 05:38

    I would suggest using client side database storage mechanisms, and let the queries do the counting for you.

    This makes it more overseeable and reduces menory warnings from various virusscanners, plus you dont need to refetch data everytime.

    Another approach would be to use a server side database and retrieve the values you want via json.

    another aproach toprevent browser freeze is to let your loop run in a webworker so its a thread and doesnt lock the browser.

    0 讨论(0)
  • 2021-01-29 05:39

    If you're free to change the structure of chartData, why not just make it a hash instead of an array?

    var chartData = {24: 0,
                     25: 0,
                     26: 0};
    

    And then the loop becomes

    for (i=0; i<timesFlipped; i++) {
        chartData[runTrial()]++;        
    }
    
    0 讨论(0)
  • 2021-01-29 05:41

    You could create another object which points to the objects in the chartData array, like so:

    var idToChart = {};
    for (var i = 0; i < chartData.length; i++) {
        var currChart = chartData[i];
        idToChart[currChart.idTag] = currChart;
    }
    

    and then use

    var chart = idToChart[totalValue];
    chart.count++;
    

    Accessing the object's property should be faster than looping through the array each time.

    If, as @zerkms pointed out, your array is sorted by idtag, you wouldn't even need to create another object and could access the array directly. Ideally, chartData would start in the idToChart or sorted array format.

    0 讨论(0)
  • 2021-01-29 05:55

    I would rather maintain a intermediate hash with a "idTag" value as a key and its count as value, perform the operation with for loop, then generate charData from the intermediate hash once the for loop completes.

    0 讨论(0)
提交回复
热议问题