Help us understand the problem. What is going on with this article?

javascriptで深い階層の確認

More than 5 years have passed since last update.

概要

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

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

※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', '見つかりませんでした');

YamasakiKenta
特にありません。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした