Home > Back-end >  Problem accessing an object's value within an equation
Problem accessing an object's value within an equation

Time:10-01

I am working on some JavaScript code that is supposed to take an inputted object and run it through a series of equations then return the object, but replacing the second key/value pair with a new key value pair calculated within the function. I have all the math correct, but I'm calling the key's value incorrectly within step 2 of the equation. A console log of the arr.avgAlt returns undefined, when it should return a number. I've repeatedly checked it against my notes and other online resources, but I still cannot tell what is wrong. I feel like I'm overlooking something obvious.

  function orbitalPeriod(arr) {
  const GM = 398600.4418;
  const earthRadius = 6367.4447;

//Step 1: get two times pi
let stepOne = 2 * Math.PI;

//Step 2: find a appears to be e radius   avg alt
/*the issue is in this line. I know I am calling the avgAlt wrong, but I'm not sure how it is wrong. 
The console log returns undefined, but it should be returning a number */ 
let stepTwo = earthRadius   arr.avgAlt;

console.log(arr.avgAlt);

//Step 3: get a^3
let stepThree= Math.pow(stepTwo, 3);

//Step 4: divide step 2 by GM defined above
let stepFour= stepTwo/GM;

//Step 5: Combo it all and round to find t
let t = Math.round(stepOne*stepFour);

//return the array w/ the new key/value pair & t is the value
 let newArr= arr.map(function(el){
    return {name:el.name,
            orbitalPeriod: t}          
  });

  return newArr;
};
orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);   

CodePudding user response:

In Step 2 change:

let stepTwo = earthRadius   arr.avgAlt

to:

let stepTwo = earthRadius   arr[0].avgAlt

Your function parameter is an object within an array. So you need to select the object location within the array and then the key you want to pull out.

  • Related