0

I am writing a generic function to iterate a jSon file as below:

function test(data, type) {
    var k = 0;

    for (var i in data) {
        k += isNaN(data[i].type) ? 0 : data[i].type;
    }

    return (k / data.length);
}

where type is a dynamic value - it can be "steps", "distance", "floors" etc

What I want to do is that every time when I call the function, it should find what type is and find the average for that type. Is there a way to do that?

jSon file is below:

[
  {
    "ActivitySummaryKey": 23323,
    "activitycalories": 768,
    "caloriesBMR": 1052,
    "caloriesOut": 1622,
    "distances": 4.14,
    "elevation": 24,
    "fairlyActiveminutes": 62,
    "floors": 8,
    "lightlyActiveMinutes": 125,
    "marginalCalories": 476,
    "sedentaryMinutes": 258,
    "steps": 5547,
    "veryActiveMinutes": 11,
    "createddate": "5/27/2014 12:00:00 AM"
  }
]
admdrew
  • 3,790
  • 4
  • 27
  • 39
sony
  • 1,453
  • 3
  • 35
  • 79
  • an example of your "generic" JSON would be handy – martskins May 27 '14 at 19:03
  • What is `period1` and `period2`. And also post sample jsOn. – dfsq May 27 '14 at 19:04
  • [json2.js](https://github.com/douglascrockford/JSON-js/blob/master/json2.js), specifically `.parse`, might help you (from [a related question](http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery?rq=1) on the sidebar). – admdrew May 27 '14 at 19:05
  • so what's the problem,you wrote a function already. – mpm May 27 '14 at 19:24
  • @mpm : this function will not work as of now, because 'type' has to be resolved dynamically – sony May 27 '14 at 19:26
  • @sony you really haven't explained your issue clearly. What do you mean by `'type' has to be resolved dynamically`. You have `type` as an argument of your function but haven't identified results you are looking for – charlietfl May 27 '14 at 19:30
  • Clearly the OP is trying to use the value of the `type` variable as property name. – Felix Kling May 27 '14 at 19:35

1 Answers1

1

If I understand you correctly, you need to modify your function to use type as the property name instead of directly accessing the data at .type.

function test(data, type) {
    var k = 0;

    for (var i in data) {
        k += isNaN(data[i][type]) ? 0 : data[i][type];
    }

    return (k / data.length);
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91