7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptで深い階層の確認

Last updated at Posted at 2015-01-06

概要

連想配列で深い階層のキーが存在するか確認します。

ない場合のデフォルトの値も設定できます。

※PHPでは、こんな感じ。

isset($a['a']['b']['c']['d'])

ソース

get = function(val, keys, def){
    var keys = String(keys).split('.');
    for(var i=0;i<keys.length && val;i++){
        val = val[keys[i]];
    }
    return val || val === false ? val : def;
}

使い方

調べたい変数を第一引数にし、第二引数にキーを.区切りで指定します。
第三引数に、見つからなかった場合 ( null or undefined ) の値を代入します。

a = {a:{b:{c:{d:'見つかりました'}}}};

// 見つかりました
get(a, 'a.b.c.d', '見つかりませんでした');

// 見つかりませんでした
get(a, 'a.aaa', '見つかりませんでした');

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?