skip to Main Content

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


  1. 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");
    
          // array of quotes for each writer
          quotes[writer].forEach(function(quoteObj) {
            // key (author's name) and value (quote) from the quote object
            const authorName = Object.keys(quoteObj)[0];
            const quote = quoteObj[authorName];
            citation.innerHTML = '"' + quote + '"';
            auteur.innerHTML = authorName;
          });
        });
    <div id="quotes-wrap"></div>

    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 using Object.keys(quoteObj)[0], and the value (quote) is obtained using quoteObj[authorName]. The auteur and citation elements’ innerHTML is then set using these values.

    Login or Signup to reply.
  2. 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.

    Object.values(quotes).flat().forEach(item => {
      let author = item.name || Object.keys(item)[0];
      let quote = item.quote || Object.values(item)[0];
     
      // build HTML output...
    });
    

    Here’s a full working example:

    const quotes = {karamazov:[{"Serge Karamazov":"Barrez vous **** de mimes."}],abitbol:[{name:"Georges Abitbol",quote:"Le train de tes injures roule sur le rail de mon indiffxe9rence."}],bath:[{name:"Hubert Bonisseur de la Bath",quote:"xc7a ne prenait pas beaucoup plus de temps."}],moulinier:[{name:"Moulinier ",quote:"L'habit ne fait pas le moine, mais il fait l'agent... Mxeame non titularisxe9."}],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.values(quotes).flat().forEach(item => {
      let author = item.name || Object.keys(item)[0];
      let quote = item.quote || Object.values(item)[0];
      createQuoteUi(author, quote);
    });
    
    function createQuoteUi(author, quote) {
      const citationWrap = document.createElement("div");
      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 = `"${quote}"`;
      auteur.innerHTML = author
      
      quotesWrap.appendChild(citationWrap);
    }
    .quote .citation {
      font-size: 1.3em;
      margin: 0;
    } 
    .quote .auteur {
      font-size: 0.8em;
      color: #666;
      margin-bottom: 30px;
    }
    <div id="quotes-wrap"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search