0

Hello I need to check 3 - dimensional json array, now I check it like this

if(events[dd][mm][rr] !== undefined){}

but if keys doesn't exists it throw's me an error. TypeError: events[dd] is undefined

I need some JS function to check if this condition is exists and throught error of TypeError. Thank you.

3 Answers 3

2

You'll have to check for each nested namespace. You could also write a recursive function if needed, if you have to check deeper into the map later on.

if (events[dd] && events[dd][mm] && events[dd][mm][rr] !== undefined) {}
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe use something like this:

function mdArrayExists(arr, var_args) {
    for (var i=1, k=arguments.length; i<k; ++i) {
        if (!arr || !arr.hasOwnProperty(arguments[i])
            return false;
        arr = arr[arguments[i]];
    }
    return true;
}

Usage:

if (mdArrayExists(events, dd, mm, rr) ...

Comments

0

I have no affiliation with this company, but whenever I need to do Array Searching work I use the underscore.js library for doing it, because it has a bunch of functions for finding data quickly, and performance wise seems to be better about overhead then if I have to iterate over arrays myself.

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.