0

I'm having some trouble with a recursive search. I want to return the block the ID was found in.

This is my data:

{
"rows": [{
    "columns": [{
        "id": "iE1YMSahu",
        "rows": [{
            "columns": [{
                "id": "VJBjVrfP"
            }, {
                "id": "NJb1234A",
                "rows": [{
                    "columns": [{
                        "id": "VJBjVXXX"
                    }, {
                        "id": "NJb1234B"
                    }]
                }]
            }]
        }]
    }, {
        "id": "EJnASD-v",
        "rows": [{
            "columns": [{
                "id": "VJBjVYYY"
            }]
        }]
    }]
}]
}

It should be returning

    {
        "id": "EJnASD-v",
        "rows": [{
            "columns": [{
                "id": "VJBjVYYY"
            }]
        }]
    }

But instead it's returning false. Here's my code:

function findColumnWithId(obj, id){
    for(var i = 0; i < obj['rows'].length; i++){
        for(var j = 0; j < obj['rows'][i]['columns'].length; j++){
            if(obj['rows'][i]['columns'][j].id == id)
                return obj;

            if(obj['rows'][i]['columns'][j].hasOwnProperty('rows')){
                var result = findColumnWithId(obj['rows'][i]['columns'][j], id);

                if(typeof result !== false)
                    return result;
            }
        }
    }

    return false;
}

findColumnWithId(data, 'VJBjVYYY');

I'm really not sure what's going on. It doesn't seem to be iterating over the last part of the Json data. This code actually does work in 5 out of my 6 use cases, which makes it even more strange. Any help would be appreciated.

3
  • 4
    Why are you writing typeof result !== false? What’s that supposed to do? Commented Jul 17, 2015 at 12:41
  • Welp, I feel stupid now. Removing typeof fixed my code (of course). I changed it from typeof result !== 'undefined to a check for false and forgot to remove the typeof. Thanks. Commented Jul 17, 2015 at 12:47
  • aren't you missing an id in the first row object? Commented Jul 17, 2015 at 12:47

1 Answer 1

1

Removing 'typeof' in this if statement fixes my code.

if(typeof result !== false)
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.