I have 5 indexed arrays in an object and I want to access these array keys to display them.
I understand that the last two lines are causing issues. I’ve searched for an hour and haven’t found why it doesnt work.
var quotes = {
karamazov: [{
"Serge Karamazov": "Barrez vous **** de mimes."
}],
abitbol: [{
name: "Georges Abitbol",
quote: "Le train de tes injures roule sur le rail de mon indifférence.",
}, ],
bath: [{
name: "Hubert Bonisseur de la Bath",
quote: "Ça ne prenait pas beaucoup plus de temps.",
}, ],
moulinier: [{
name: "Moulinier ",
quote: "L'habit ne fait pas le moine, mais il fait l'agent... Même non titularisé.",
}, ],
welles: [{
name: "Orson Welles",
quote: "C'est du vol et du plagiat. j'aime pas trop les voleurs et...",
}, ],
};
const quotesWrap = document.querySelector('#quotes-wrap');
Object.keys(quotes).forEach(function(writer) {
const citationWrap = document.createElement("div");
quotesWrap.appendChild(citationWrap);
const citation = document.createElement("p");
const auteur = document.createElement("p");
citationWrap.appendChild(citation);
citationWrap.appendChild(auteur);
citationWrap.classList.add("quote");
citation.classList.add("citation");
auteur.classList.add("auteur");
citation.innerHTML = '"' + writer.quote + '"';
auteur.innerHTML = writer.name;
});
<div id="quotes-wrap"></div>
2
Answers
The array of quotes for each writer can be accessed using
quotes[writer]
. Next, the key (author’s name) for each quote object in the array is obtained usingObject.keys(quoteObj)[0]
, and the value (quote) is obtained usingquoteObj[authorName]
. The auteur and citation elements’ innerHTML is then set using these values.The issue with your code is due to how you access the entities as you iterate over them. In your case
writer
will hold the key of the object only, not the name of the author or their quote.To fix this you can instead use
Object.values()
to get the values from the source which can be flattened in to a single array.You also have the additional problem that the first item in the array is in a different format to the others, where the author name/quote are the key/value of the object, whereas the others are kept in a more usable format with consistent separated key/values.
To address this you can have some simple logic to check both values if one fails to retrieve the data you require like this – although note that the best solution would be to have all the data in a consistent structure to avoid needing to do this at all.
Here’s a full working example: