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

后端 未结 4 1005
眼角桃花
眼角桃花 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: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.

提交回复
热议问题