Write a function named "json_average" that takes a JSON formatted string as a parameter in the format of an array of objects where each object has keys "mass", "density", "temperature", and "velocity" and each key maps to a floating point number. This function should return the average "velocity" of all the objects in the array as a JSON string in the format {"velocity": }
function json_average(JSON1){
var load = JSON.parse(JSON1);
var sum = 0;
var sum1 = 0;
var dictionary = {};
for (var i in load){
sum += i.velocity;
sum1 += 1;
}
var average = sum / sum1;
dictionary.velocity = average;
return JSON.stringify(dictionary);
}
console.log(json_average('[{"velocity": 1}, {"velocity": 10}]'));
I keep returning the value of 'velocity' as null. What am I doing wrong?
Because it's an array, you want to use for i of load
:
function json_average(JSON1) {
var load = JSON.parse(JSON1);
var sum = 0;
var sum1 = 0;
var dictionary = {};
for (var i of load) {
sum += i.velocity;
sum1 += 1;
}
var average = sum / sum1;
dictionary.velocity = average;
return JSON.stringify(dictionary);
}
console.log(json_average('[{"velocity": 1}, {"velocity": 10}]'));
for...in
is used to iterate over keys of an object.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments