Estoy tratando de asignar múltiples elementos y matrices anidadas para representar varios archivos mp3. A cada elemento de la matriz se le asignarán varios elementos únicos
const sermon = { id: "", topic: "", book: "", bookPart: "", path: "", file: "", fileType: "", sermonName: function() { return (this.book + " " + this.bookPart).toUpperCase(); } };Así que básicamente me gustaría
sermon[0] = { id: "01" topic: "New Testament", book: "Hebrews", bookPart: "Part 1", path: "sermons/" + sermon.book, file: "hebrews_part1.mp3", fileType: "mp3", sermonName: "HEBREWS PART 1"El "id, libro, tema" sería el mismo para cada "sermon.bookPart, sermon.file". Para cada libro, la "identificación, el libro y el tema" cambiarían (como se esperaba)
Escribiría a lo siguiente:
<h3 id="demo"></h3> <p id="topic"></p> <p id="book"></p> <p id="file"></p> <p id="path"></p> document.getElementById("demo").innerHTML = sermon.sermonName(); document.getElementById("topic").innerHTML = sermon.topic; document.getElementById("book").innerHTML = sermon.book; document.getElementById("file").innerHTML = sermon.file; document.getElementById("path").innerHTML = sermon.path;Intenté completar manualmente y asignar matrices, pero me quedé atascado al intentar hacer 3 bucles for anidados para agregar "Parte 1,2,3" con las matrices book[]
let x = ""; const sermon = { topic: "New Testament", path: "sermons/", book: [ { name: "Hebrews", files: ["hebrews_part1.mp3", "hebrews_part2.mp3", "hebrews_part3.mp3"] }, { name: "1Corinthians", files: ["1cor_part1.mp3", "1cor_part2.mp3", "1cor_part3.mp3"] } ] }; for (let i in sermon.book) { x += "<h3>" + sermon.book[i].name + "</h3>"; for (let j in sermon.book[i].files) { x += "<a href=" + sermon.path + sermon.book[i].name + "/" + sermon.book[i].files[j] + ">" + sermon.book[i].files[j] + "</a><br>"; }; };Por lo tanto, deberá convertir el objeto del sermon en otra matriz.
const sermons = [ topic: "New Testament", path: "sermons/", book: [ { name: "Hebrews", files: ["hebrews_part1.mp3", "hebrews_part2.mp3", "hebrews_part3.mp3"] }, { name: "1Corinthians", files: ["1cor_part1.mp3", "1cor_part2.mp3", "1cor_part3.mp3"] } ], ... // add more sermons here ] }; luego puede iterar sobre los sermones usando otro bucle for. Desafortunadamente, esto es solo un resultado de la estructura. Lo que puede hacer es crear una nueva variable para hacer referencia al nivel actual de iteración, es decir, sermons es el objeto de nivel superior, pero cada sermon es solo otro nombre para sermons[h] , sermon.book[i] se convierte en book , etc. , de esa manera es un poco más fácil visualizar lo que estás usando.
for (let h in sermons) { let sermon = sermons[h]; for (let i in sermon.book) { let book = sermon.book[i]; x += "<h3>" + book.name + "</h3>"; for (let j in book.files) { x += "<a href=" + sermon.path + book.name + "/" + book.files[j] + ">" + book.files[j] + "</a><br>"; } } }