0
0

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 3 years have passed since last update.

JavaScriptでネストしたオブジェクトの存在チェック

Last updated at Posted at 2020-02-25

ネストしたオブジェクトにアクセスするときに、存在チェックが出来る関数を作りました。

deepメソッド

const deep = (obj, path) => {
  path = path.split(/\.|\[|\]/).filter(v => v)
  for (const k in path) {
    if (!obj) return false
    else if (obj[path[k]]) obj = obj[path[k]]
    else return false
  }
  return true
}

使い方

testオブジェクトに、test2プロパティが存在している
その中にtest3プロパティが存在していて、かつ中の値も存在しているか確認

const test = {
  test2: {
    test3: true
  }
}

console.log(deep(test, 'test2.test3'))

出力結果

true

存在している場合はtrue、存在していない場合はfalseが返ってくる

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?