0

I am trying to get a json response, save it to an array and loop through it to look for matches. However, I am having some difficulties.

I get the json response, and push it to an array with:

var array = Object.entries(response);

After that I have let's say this array:

var array = [
    [
        "default_route",
        { 
            "subnet": "0.0.0.0/0", 
            "name": "Default" 
        }
    ],
    [
        "vpn_subnet",
        "192.168.10.0/24"
    ]
];

It still has some objects inside. Now when I try to loop through it I get no output. It's like the loop doesn't even start. Console doesn't print anything. Example of loop:

for (var i = 0; i < array.length; i++) {
    console.log('loop');
    for (var j = 0; j < array[i]; j++) {
        console.log('loop 2');
    }
};

Do I have to convert objects to array values first? The json response I get is a lot more detailed and has a lot more objects in it, compared to snippet above. Ultimately I want to loop through the json response and find a match. What's the best way of doing this?

4
  • 3
    if you don't see loop in the console then your array is empty at the time of running the loop. Your array may be being populated asynchronously, so when you run your loop, your array isn't populated yet. Can you show how you get your array and where you run your loop in relation to that? Commented Mar 14, 2020 at 2:58
  • 1
    Try with j < array[i].length in your second loop. Commented Mar 14, 2020 at 3:04
  • @Camilo That works! Additional question, is there a way to convert object to array once the loop gets to that part? Like the part with "subnet" and "name". Commented Mar 14, 2020 at 3:11
  • That would be a separated question @PujdoP. Commented Mar 14, 2020 at 3:23

1 Answer 1

1

The condition on your 2nd loop won't work because array[i] returns another array instead of a number. Try appending .length to it, something like:

for (var i = 0; i < array.length; i++) {
    console.log('loop');
    for (var j = 0; j < array[i].length; j++) {
        console.log('loop 2');
    }
};
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.