Embet Isit
Embet Isit

Reputation: 321

How do you add a counter numbering for a loop of a loop?

My data looks like this

posts : {
    author1 : {
        "article1" : { },
        "article2" : { }
    },
    author2 : {
        "article1" : { },
        "article2" : { }
    }

I have a counter that loops through articles and numbers Object.keys().map((key)=>.. and then displays counter for each article key + 1 etc. Works perfectly fine but now i want to display all authors and show all articles.

My UI looks like this

Author1

  1. Article
  2. Article

Author2

  1. Article
  2. Article

I want to change be like this

Author1

  1. Article1
  2. Article2

Author2

  1. Article1
  2. Article2

How do i make the second loop start from the end author1

Upvotes: 1

Views: 80

Answers (1)

guest271314
guest271314

Reputation: 1

You can use Object.entries() to iterate both properties and values of an object. Note, there are duplicate property names at code at Question

const posts = {
  author1: {
    "article1": {a:1},
    "article2": {b:2}
  },
  author2: {
    "article1": {c:3},
    "article2": {d:4}
  }
}

for (let [key, prop] of Object.entries(posts)) {
  console.log(`${key}:\n`);
  for (let [item, articles] of Object.entries(prop)) {
    console.log(`${item}:${JSON.stringify(articles)}\n`);      
  } 
}

Upvotes: 1

Related Questions