0

I have an object obj1 with another object inside obj2.

obj2 is structured in the same way as obj1 so there will be another object inside it.

Let's say that I have 20 of these and I'm trying to get inside each one of them to get some data.

Is there a way to create a loop that goes inside an obj as soon as it sees it?

I tried doing this but with no luck.

var location;
for (var [key, value] of Object.entries(object)) {
  var type = typeof value;
  var array = Array.isArray(value);
  if (typeof value === "object" && array === false && value) {
    location = key;
    for (var [a, b] of Object.entries(object[location])) {
      /*this is where I'm stuck, the location variable doesn't update with
      the 'path' of every object*/
    }
  }
}
3
  • 1
    What's your expected output? What do you wanna achieve with this? Maybe there's a simpler way of doing it. Commented Oct 19, 2020 at 10:47
  • Agree with Vishnudev, to help you we really need to see what the original object looks like and what you are trying to get from it. On the surface it does look like you need a recursive function as suggested by Bulent but more detail will help us be more accurate and informative Commented Oct 19, 2020 at 10:57
  • The expected output would be to print in an HTML page the objects using an ul li list, so I didn't know how to get in all the objects and how to put them in a list giving them some sort of indentation. js <ul> <li>obj1</li> <ul> <li>obj2</li> <ul> <li>obj3</li> </ul> </ul> </ul>; I did the first part and now I don't know how to indent the list :c Commented Oct 19, 2020 at 11:34

1 Answer 1

1

Create a function that loop on one level. Check values for objects. If you find one, recall the same function.

function createLoop(obj) {
  for (const key in obj) {
     if (typeof obj[key] == "object") {
        createLoop(obj[key])
     } else {
       // do your stuff
     }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.