简体   繁体   中英

How to iterate a forEach over an object/array/key values from axios in JS (make DRY)?

I'm struggling to condense this code into one forEach loop to make my code dry. The image shows the console.log(res) for what I'm working with.

图像响应

Here is my code:

   .get('https://website.went.here/articles')
        .then((res) => { 
            const articles = res.data.articles;
            const js = articles.javascript;
            const bs = articles.bootstrap;
            const jq = articles.jquery;
            const node = articles.node;
            const tech = articles.technology;

            i = 0;

           console.log(articles.values(res));

            js.forEach((item) => {
                card.appendChild(cardCreator(item))
            });
            bs.forEach((item) => {
                card.appendChild(cardCreator(item))
            });
            jq.forEach((item) => {
                card.appendChild(cardCreator(item))
            });
            node.forEach((item) => {
                card.appendChild(cardCreator(item))
            });
            tech.forEach((item) => {
                card.appendChild(cardCreator(item))
            }); 

You can use Object.keys to get an object's keys.

For example,

const obj = {"javascript": [...], "python": [...], "bootstrap": [...]}

Object.keys(obj) will output ["javascript", "python", "bootstrap"] .

From there, you can store that array as a variable, then iterate over those keys like so:

const keys = Object.keys(obj);
keys.forEach(key => {
  obj[key]...
})

Make an array of properties that you need to iterate over, iterate over those properties, and for each property, iterate over all elements in the property array and append:

.get('https://website.went.here/articles')
  .then((res) => {
    const { articles } = res.data;
    for (const prop of ['javascript', 'bootstrap', 'jquery', 'node', 'technology']) {
      for (const item of articles[prop]) {
        card.appendChild(cardCreator(item));
      }
    }
  });

Or, if you have to use forEach :

.get('https://website.went.here/articles')
  .then((res) => {
    const { articles } = res.data;
    ['javascript', 'bootstrap', 'jquery', 'node', 'technology'].forEach((prop) => {
      articles[prop].forEach((item) => {
        card.appendChild(cardCreator(item));
      });
    });
  });

If the order of the properties being appended doesn't matter, you can make it easier by simply iterating over the object values of the articles object:

.get('https://website.went.here/articles')
  .then((res) => {
    for (const arr of Object.values(res.data.articles)) {
      for (const item of arr) {
        card.appendChild(cardCreator(item));
      }
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM