Jump to content

Javascript: how to loop an array over and over again?

Go to solution Solved by QQ_cazo,

Solved:

function gothru(array,data) {
    if (data) {
        console.log(array.id+"|"+array.parent_id)
    } else {
        console.log(array.id)
    }
    if (Object.keys(array.children_comments).length >= 1) {
      	// i forgot that this was an ARRAY, so now it works for any number of comments.
        array.children_comments.forEach(element => {
            gothru(element,true)
        });
    }

}
JSON.parse(a).forEach(element => {
    gothru(element)
});

 

my goal: for every "comment" load the childen (and run another function) and do the same for their childern etc etc etc.

my test data = 

[
  {
    "auth": "true",
    "children_comments": [
      {
        "auth": "true",
        "children_comments": [
          "can go on forever":true
        ],
        "comment": "<i>deleted</i>",
        "date": "5 months ago",
        "id": 784,
        "isOP": "false",
        "name": "<i>deleted</i>",
        "parent_id": 783,
        "user_icon": "{{URL}}"
      }
    ],
    "comment": "<i>deleted</i>",
    "date": "5 months ago",
    "id": 783,
    "isOP": "false",
    "name": "<i>deleted</i>",
    "parent_id": 777,
    "user_icon": "{{URL}}"
  }
]

my python code that makes this array=

  comments_by_parent = defaultdict(list)
  for comment in data:
      comments_by_parent[comment['parent_id']].append(comment)

  for comment in data:
      comment['children_comments'] = comments_by_parent[comment['id']]

ive tried simple For loops, For IN loops and nothing seems to work

 

update: tried this, getting closer but not the same result

function gothru(array) {
    if (Object.keys(array.children_comments).length >= 1) {
        console.log(array.children_comments)
        gothru(array.children_comments) //breaks here typeError: Cannot convert undefined or null to object
        return
        if (Object.keys(array.children_comments).length >=1) {
            console.log("e")
            gothru(array.children_comments)
        }
    }

}
JSON.parse(a).forEach(element => {
    gothru(element)
});

 

Link to post
Share on other sites

Solved:

function gothru(array,data) {
    if (data) {
        console.log(array.id+"|"+array.parent_id)
    } else {
        console.log(array.id)
    }
    if (Object.keys(array.children_comments).length >= 1) {
      	// i forgot that this was an ARRAY, so now it works for any number of comments.
        array.children_comments.forEach(element => {
            gothru(element,true)
        });
    }

}
JSON.parse(a).forEach(element => {
    gothru(element)
});

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×