underscore-keypath
key-path mechanism extensions for underscore (mixin).
underscore-keypath let you access JavaScript objects and arrays with keypath easily.
1var foo = { 2 bar : { 3 name : "Cool!" 4 }, 5 scores : [55, 27, 100, 33] 6}; 7 8_(foo).valueForKeyPath("bar.name"); // --> "Cool!" 9_(foo).setValueForKeyPath("bar.name", "BAR"); // --> sets foo.bar.name as "BAR" 10_(foo).valueForKeyPath("scores.@max"); // --> 100
Install
NodeJS
$ npm install underscore-keypath
1var _ = require("underscore-keypath");
or you may want to use origianl underscore:
1var _ = require("underscore"); 2require("underscore-keypath"); // it will extend original underscore
in this case, please install "underscore" first.
$ npm install underscore $ npm install underscore-keypath
Otherwise, underscore-keypath extends separated underscore in sandbox.
Meteor
$ meteor add jeeeyul:underscore-keypath
Front-end
$ bower install underscore-keypath
Or just download underscore-keypath.js manually.
Examples
1var list = [{ 2 name : "foo", 3 info : { 4 favoriteColor : "red", 5 age : 20 6 } 7},{ 8 name : "bar", 9 info : { 10 favoriteColor : "green", 11 age : 17 12 } 13},{ 14 name : "zar", 15 info : { 16 favoriteColor : "red", 17 age : 34 18 } 19}]; 20 21_(list).pluckByKeyPath("info.age"); // --> [20, 17, 34] 22_(list).sortByKeyPath("info.age"); // --> [{name:"bar", ..}, {name:"foo", ..}, {name:"zar", ..}] 23_(list).groupByKeyPath("info.favoriteColor"); // --> {red:2, green:1} 24
See API Document