10
10

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のオブジェクトにドット記法でアクセスする

Posted at

例えば以下の様なオブジェクトがあったとする

obj = {
  hoge : {
    fuga : {
       bar : "bar"
    }
  }
}

このとき、barの値にアクセスする場合、どうするか、という話。jsでネストされたオブジェクトのプロパティにアクセスする場合、ドット記法か多次元配列かが選択できるが、場合によってはkey pathが変数で渡されてくる場合がある。そういう場合に


// エラー
var bar = obj["hoge.fuga.bar"]

とやると普通にエラーになる。なので以下の様なアクセサを作って使う

function accessWithDots(obj,key_path) {
  var key, paths, val;
  paths = key_path.split(".");
  val = obj;
  while (paths.length > 0) {
    key = paths.shift();
    val = val[key];
  }
  return val;     
}

var bar = accessWithDots(obj,"hoge.foo.bar")
// => bar
10
10
1

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
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?