Skip to content
Jeeeyul Lee edited this page Feb 7, 2014 · 38 revisions

valueForKeyPath(obj, keyPath, fallbackValue)

Returns value for given key path("." separated property names)

  • obj : An object to get value of property.
  • keyPath : "." separated property path.
  • fallbackValue : fallback value which will be retuned when there is no matching value for given key path.
var obj = {
  foo : {
    bar : "test"
  }
};

_(obj).valueForKeyPath("foo.bar"); // --> "test"
_(obj).valueForKeyPath("foo.notExistingProperty", "fallback"); // --> "fallback"

getter

What if there is a getter for given keypath, underscore-keypath tries to use it.

var bar = {
  _name : "Hello",
  _valid : true
};

bar.getName = function(){
  return this._name;
};

bar.isValid = function(){
  return this._valid;
}

_(bar).valueForKeyPath("name"); // --> "Hello"
_(bar).valueForKeyPath("valid"); // --> true

var foo = {
  "bar" : bar
};

_(foo).valueForKeyPath("bar.name") // --> Hello
//                      ^^^ 
//                        will be passed as "this" to getter

Access Array

var obj = {
  data : ["foo", "bar"]
};

_(obj).valueForKeyPath("data.0"); // --> "foo"

What if current context is an instance of Array, You can use element selector on your key path.

  • @first : first element
  • @last : last element
  • @max : max value element
  • @min : min value element
  • @size : size of array
var elements = [
  {
     data : [1, 2, 3, 4, 5]
  },
  {
     data : [10, 20, 30, 40, 50]
  }
]

_(elements).valueForKeyPath("@first.@size"); // --> 5
_(elements).valueForKeyPath("@last.@max"); // --> 50

setValueForKeyPath(obj, keyPath, newValue)

Do you really need description for this function? Really?

Extensions for collection

pluckByKeyPath(list, keyPath)

var list = [
  {
    foo : {
      bar : "first"
    }
  },
  {
    foo : {
      bar : "second"
    }
  }
];

_(list).pluckByKeyPath("foo.bar"); // --> ["first", "second"]

whereByKeyPath(list, query)

findWhereByKeyPath(list, query)

Clone this wiki locally