Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/component/to-function
Convert property access strings to a function ("user.name.first" etc)
https://github.com/component/to-function
Last synced: 3 days ago
JSON representation
Convert property access strings to a function ("user.name.first" etc)
- Host: GitHub
- URL: https://github.com/component/to-function
- Owner: component
- Created: 2012-09-20T17:12:53.000Z (over 12 years ago)
- Default Branch: master
- Last Pushed: 2015-03-12T01:25:50.000Z (almost 10 years ago)
- Last Synced: 2024-10-30T03:57:25.258Z (about 2 months ago)
- Language: JavaScript
- Size: 304 KB
- Stars: 65
- Watchers: 7
- Forks: 10
- Open Issues: 0
-
Metadata Files:
- Readme: Readme.md
- Changelog: History.md
Awesome Lists containing this project
README
# to-function
Convert property access strings into functions
## Installation
$ component install component/to-function
## Examples
```js
var toFunction = require('to-function');
var fn = toFunction('name.first');
var user = { name: { first: 'Tobi' }};
fn(user);
// => "Tobi"
```### Dot access
```js
var _ = require('..');
var users = [
{ name: { first: 'Tobi' }},
{ name: { first: 'Loki' }},
{ name: { first: 'Jane' }},
{ name: { first: 'Manny' }}
];var short = users.map(_('name.first'));
console.log(short);
// => [ 'Tobi', 'Loki', 'Jane', 'Manny' ]
```### Equality
```js
var _ = require('..');var tobi = { name: { first: 'Tobi' }, age: 2 };
var loki = { name: { first: 'Loki' }, age: 2 };
var jane = { name: { first: 'Jane' }, age: 6 };var users = [tobi, loki, jane];
var user = users.filter(_(loki)).pop();
console.log(user);
// => { name: { first: 'Loki' }, age: 2 }
```### Expressions
```js
var _ = require('..');var users = [
{ name: { first: 'Tobi' }, age: 2 },
{ name: { first: 'Loki' }, age: 2 },
{ name: { first: 'Jane' }, age: 6 }
];var oldPets = users.filter(_('age > 2 && age < 10'));
console.log(oldPets);
// => [ { name: { first: 'Jane' }, age: 6 } ]
```### Regular expressions
```js
var _ = require('..');var users = [
'Tobi',
'Loki',
'Jane'
];var t = users.filter(_(/^T/));
console.log(t);
// => [ 'Tobi' ]
```### Nesting
```js
var _ = require('..');var users = [
{ name: { first: 'Tobi', last: 'Ferret' }, age: 2 },
{ name: { first: 'Loki', last: 'Ferret' }, age: 2 },
{ name: { first: 'Luna', last: 'Cat' }, age: 2 },
{ name: { first: 'Manny', last: 'Cat' }, age: 3 }
];// single-key
var query = _({
name: {
last: 'Cat'
}
});console.log(users.filter(query));
// => [ { name: { first: 'Luna', last: 'Cat' }, age: 2 },
// { name: { first: 'Manny', last: 'Cat' }, age: 3 } ]// multi-key
var query = _({
name: {
first: /^L/,
last: 'Cat'
}
});console.log(users.filter(query));
// => [ { name: { first: 'Luna', last: 'Cat' }, age: 2 } ]// multi-level
var query = _({
name: { last: 'Cat' },
age: 3
});console.log(users.filter(query));
// => [ { name: { first: 'Manny', last: 'Cat' }, age: 3 } ]
```## License
MIT