koca79331
koca79331

Reputation: 421

Javascript check multidimensional array if keys exists

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.

Upvotes: 0

Views: 1560

Answers (3)

Mark
Mark

Reputation: 861

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.

Upvotes: 0

dcode
dcode

Reputation: 614

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) ...

Upvotes: 0

Shilly
Shilly

Reputation: 8589

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) {}

Upvotes: 2

Related Questions