filter-where
Filter an array using any combination of scalars, object queries, functions or regular expressions.
where(query) ⇒ function
⏏
Kind: Exported function
Param | Type | Description |
---|
query | any | Array.<any> | one or more queries |
Example
Say you have a recordset:
> data = [
{ name: 'Dana', age: 30 },
{ name: 'Yana', age: 20 },
{ name: 'Zhana', age: 10 }
]
You can return records with properties matching an exact value:
> data.filter(where({ age: 10 }))
[ { name: 'Zhana', age: 10 } ]
or where NOT the value (prefix the property name with !
)
> data.filter(where({ '!age': 10 }))
[ { name: 'Dana', age: 30 }, { name: 'Yana', age: 20 } ]
match using a function:
> function over10(age){ return age > 10; }
> data.filter(where({ age: over10 }))
[ { name: 'Dana', age: 30 }, { name: 'Yana', age: 20 } ]
match using a regular expression
> data.filter(where({ name: /ana/ }))
[ { name: 'Dana', age: 30 },
{ name: 'Yana', age: 20 },
{ name: 'Zhana', age: 10 } ]
You can query to any arbitrary depth. So with deeper data, like this:
> deepData = [
{ name: 'Dana', favourite: { colour: 'light red' } },
{ name: 'Yana', favourite: { colour: 'dark red' } },
{ name: 'Zhana', favourite: { colour: [ 'white', 'red' ] } }
]
get records with favourite.colour
values matching /red/
> deepData.filter(where({ favourite: { colour: /red/ } }))
[ { name: 'Dana', favourite: { colour: 'light red' } },
{ name: 'Yana', favourite: { colour: 'dark red' } } ]
if the value you're looking for maybe part of an array, prefix the property name with +
. Now Zhana is included:
> deepData.filter(where({ favourite: { '+colour': /red/ } }))
[ { name: 'Dana', favourite: { colour: 'light red' } },
{ name: 'Yana', favourite: { colour: 'dark red' } },
{ name: 'Zhana', favourite: { colour: [ 'white', 'red' ] } } ]
you can combine any of the above by supplying an array of queries. Records will be returned if any of the queries match:
> const nameBeginsWithY = { name: /^Y/ }
> const faveColourIncludesWhite = { favourite: { '+colour': 'white' } }
> deepData.filter(where([ nameBeginsWithY, faveColourIncludesWhite ]))
[ { name: 'Yana', favourite: { colour: 'dark red' } },
{ name: 'Zhana', favourite: { colour: [ 'white', 'red' ] } } ]
© 2016-18 Lloyd Brookes <75pound@gmail.com>. Documented by jsdoc-to-markdown.