Quiero calcular el promedio de una matriz que consta de objetos anidados. Ahora, el problema es que lo que tengo ahora está extremadamente codificado, pero tampoco depende de la profundidad de la matriz. Imagine que el ejemploArray también obtuvo dos claves nuevas debajo de cada curso llamadas "mitad del período" y "período completo", por ejemplo, donde todas tenían entre 15 y 17 años, entonces mi código dejará de funcionar. Estoy extrayendo de una API que tiene diferentes profundidades en los objetos anidados. ¿Hay alguna manera de hacer que esto funcione sin depender de la codificación como ahora?
const courses = ["math", "english", "geography"] const exampleArray = [{ name: "Tim", class: "C", value: { //key is age and key is percentage on test he had at that age math: { "15": 46, "16": 49, "17": 97 }, english: { "15": 21, "16": 20, "17": 0 }, geography: { "15": 96, "16": 31, "17": 88 } } }, { name: "Jack", class: "C", value: { //key is age and key is percentage on test he had at that age math: { "15": 49, "16": 15, "17": 96 }, english: { "15": 21, "16": 20, "17": 56 }, geography: { "15": 0, "16": 38, "17": 77 } } }, { name: "Catherine", class: "C", value: { math: { //key is age and key is percentage on test he had at that age "15": 44, "16": 19, "17": 93 }, english: { "15": 0, "16": 28, "17": 59 }, geography: { "15": 14, "16": 18, "17": 27 } } } ] const courseArray = Object.keys(exampleArray[0].value) const course = [courseArray[0]] const ageArray = Object.keys(exampleArray[0].value[course]); function CalcAvg(course, ageArray) { const emptyObject = {} ageArray.map((age) => { const val =(exampleArray.map(function(obj) { return obj.value[course][age] }) .reduce(function(a, b) { return a + b }) / exampleArray.length) emptyObject[age] = val }) return emptyObject } const testObject = {Class:"C",value:{}} courseArray.map((course) => { testObject["value"][course] = CalcAvg(course, ageArray) }) console.log(testObject)