10
11

More than 5 years have passed since last update.

lodash の path を使う関数でオブジェクト操作が便利になる

Last updated at Posted at 2018-06-30

JavaScript を使っているなら lodash は大変便利なのですが、関数が多すぎてどれ使ったらいいのか解りづらいのが難点です。

ここではその中でも 'a.b[0].c' のような path を使ってオブジェクトを操作できる関数が便利なので紹介します。

値取得

get, at, result, invoke

var object = { 'a': [{ 'b': { 'c': 3, 'd': _func(4) } }, 5, [1, 2, 3, 4]] };

_.get(object, 'a[0].b.c')           // => 3          // 単一の値を得る
_.get(object, 'a[99].z.y')          // => undefined  // ヌルポは出ないので便利
_.get(object, ['a', '0', 'b', 'c']) // => 3          // path は配列でもいい
_.get(object, 'a.b.c', 'default')   // => 'default'  // デフォルト値の指定も可能

_.result(object, 'a[0].b.d')                   // => 4 // 関数として実行し、その結果を返す
_.result(object, 'a[0].b.c')                   // => 3 // 関数じゃないなら、get と同様
_.result(object, 'a[0].b.e', _func('default')) // => 'default'
_.result(object, 'a[0].b.e', 'default')       // => 'default'

_.invoke(object, 'a[1].slice', 1, 3)           // => [2, 3] // 関数として実行。引数を渡せる

_.at(object, ['a[0].b.c', 'a[1]']) // => [3, 5] // 複数のパスを指定して、値の配列を得る

パスの存在チェック

has, hasIn

var object = { 'a': { 'b': 2 } };
var other = _.create({ 'a': { 'b': 2 } }); // 継承した子クラスを作る

_.has(object, 'a.b') // => true
_.has(other, 'a')    // => false // 親クラスまでは辿らない

_.hasIn(other, 'a')    // => false // 親クラスを辿る
  • In はたぶん inherited (継承された) の略。

更新

set, update, unset

var object = { 'a': [{ 'b': { 'c': 3 } }] };

// 単純な更新
_.set(object, 'a[0].b.c', 4); // object.a[0].b.c を 4 に更新
_.set(object, 'z[0].b.c', 4); // object.z[0].b.c を追加。中間の object や array が無ければ作成する

// 関数で更新
_.update(object, 'a[0].b.c', n => n * n); // object.a[0].b.c を 9 に更新
_.update(object, 'x[0].y.z', n => n ? n + 1 : 0); // キーが存在しないなら undefined

// キー削除
_.unset(object, 'a[0].b.c'); // { 'a': [{ 'b': {} }] } に更新して true (更新した) を返す
  • いずれも引数で渡した object 自体を変更する (破壊的)

lodash関連の記事

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