A collection of Vue.js filters, based on underscore.js.
You will only use few filters in your project, and you don't need all of those filters. Please consider using a library like Lodash and write the filter you needed by yourself.
I will no longer maintain this repo, since importing a large colloections of filters but using a few is not a good practice. And all of those filters can be implemented with Lodash or underscore.js in a few lines of code.
You can install it from npm:
npm install vue-filter --save
or copy the file at here.
If you include the file with <script>
tag, the filters will be installed automatically. But please make sure put the vue-filter
script behind Vue.
<script src="vue.min.js"></script>
<script src="vue-filter.min.js"></script>
If you use a bundle tools like webpack, you need install the filters manually.
As from Vue 2.0 you have to install the extension using the Vue.use()
sytax.
import VueFilter from 'vue-filter';
import Vue from 'vue';
// Vue.install(vueFilter); // Vue V1
Vue.use(VueFilter); // Vue V2
data: {
list: [{
name: 'James, LeBron',
score: 38
},{
name: 'Irving, Kyrie',
score: 43
},{
name: 'Jefferson, Richard',
score: 11
}]
}
// get sum of score.
{{ list | map(player => player.score) | sum }} => 92
// top score.
{{ list | max(player => player.score) | get('score') }} => 43
Click the filter to see how to use it.
- map
- at
- reduce
- find
- filter
- reject
- every
- some
- contains
- pluck
- max
- min
- sortBy
- groupBy
- indexBy
- countBy
- shuffle
- sample
- toArray
- size
- append
- prepend
- camelcase
- replace
- substring
- substr
- truncate
- split
- trim
- trimLeft
- trimRight
- test
- leftPad
- rightPad
- repeat
- lowercase
- uppercase
- nl2br
- abs,acos,asin,atan,atan2,ceil,cos,exp,floor,log,pow,round,sin,sqrt,tan
- sum
- mean
- plus
- minus
- multiply
- divide
- mod
- toFixed
- toPrecision
Produces a new array of values by mapping each value in list through a transformation function (iteratee). The iteratee is passed three arguments: the value
, then the index
(or key
) of the iteration, and finally a reference to the entire list
.
{{ [1,2,3] | map(function (n){ return n * 2; }) }} => [2,4,6]
{{ [1,2,3] | map(function (num){ return num * 3; }) }} => [3,6,9]
{{ {"one":1,"two":2,"three":3} | map(function (num, key){ return num * 3; }) }} => [3,6,9]
Returns the item at the specified index location in an array or a string.
{{ ['a','b','c'] | at(1) }} => 'b'
{{ 'hello' | at(1) }} => 'e'
Also known as inject and foldl, reduce boils down a list of values into a single value. Memo is the initial state of the reduction, and each successive step of it should be returned by iteratee. The iteratee is passed four arguments: the memo
, then the value
and index
(or key) of the iteration, and finally a reference to the entire list
.
If no memo is passed to the initial invocation of reduce, the iteratee is not invoked on the first element of the list. The first element is instead passed as the memo in the invocation of the iteratee on the next element in the list.
{{ [1,2,3] | reduce(function (memo, num){ return memo + num; }, 0) }} => 6
Looks through each value in the list, returning the first one that passes a truth test (predicate), or undefined
if no value passes the test. The function returns as soon as it finds an acceptable element, and doesn't traverse the entire list.
{{ [1,2,3,4,5,6] | find(function (num){ return num % 2 == 0; }) }} =>
Looks through each value in the list, returning an array of all the values that pass a truth test (predicate).
{{ [1,2,3,4,5,6] | filter(function (num){ return num % 2 == 0; }) }} => [2,4,6]
Returns the values in list without the elements that the truth test (predicate) passes. The opposite of filter.
{{ [1,2,3,4,5,6] | reject(function (num){ return num % 2 == 0; }) }} => [1,3,5]
Returns true if all of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a false element is found.
{{ [2,4,5] | every(function (num) { return num % 2 == 0; }) }} => false
Returns true if any of the values in the list pass the predicate truth test. Short-circuits and stops traversing the list if a true element is found.
{{ [null,0,"yes",false] | some(val => !val ) }} => true
Returns true if the value is present in the list. Uses indexOf internally, if list is an Array. Use fromIndex to start your search at a given index.
{{ [1,2,3] | contains(3) }} => true
A convenient version of what is perhaps the most common use-case for map: extracting a list of property values.
{{ [{
"name": "moe",
"age": 40
}, {
"name": "larry",
"age": 50
}, {
"name": "curly",
"age": 60
}] | pluck("name") }} => ["moe","larry","curly"]
Returns the maximum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. -Infinity is returned if list is empty, so an isEmpty guard may be required. Non-numerical values in list will be ignored.
{{ [{
"name": "moe",
"age": 40
}, {
"name": "larry",
"age": 50
}, {
"name": "curly",
"age": 60
}] | max(function (stooge){ return stooge.age; }) }} => {"name":"curly","age":60}
Returns the minimum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. Infinity is returned if list is empty, so an isEmpty guard may be required. Non-numerical values in list will be ignored.
{{ [10,5,100,2,1000] | min }} => 2
Returns a (stably) sorted copy of list, ranked in ascending order by the results of running each value through iteratee. iteratee may also be the string name of the property to sort by (eg. length
).
{{ [1,2,3,4,5,6] | sortBy(function (num){ return Math.sin(num); }) }} => [5,4,6,3,1,2]
{{ [{
"name": "moe",
"age": 40
}, {
"name": "larry",
"age": 50
}, {
"name": "curly",
"age": 60
}] | sortBy("name") }}
=>
[{
"name": "curly",
"age": 60
}, {
"name": "larry",
"age": 50
}, {
"name": "moe",
"age": 40
}]
Splits a collection into sets, grouped by the result of running each value through iteratee. If iteratee is a string instead of a function, groups by the property named by iteratee on each of the values.
{{ [1.3, 2.1, 2.4] | groupBy(function (num){ return Math.floor(num); }) }} => {"1":[1.3],"2":[2.1,2.4]}
{{ ["one","two","three"] | groupBy("length") }} => {"3":["one","two"],"5":["three"]}
Given a list, and an iteratee function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
{{ [{
"name": "moe",
"age": 40
}, {
"name": "larry",
"age": 50
}, {
"name": "curly",
"age": 60
}] | indexBy("age") }} =>
{
"40": {
"name": "moe",
"age": 40
},
"50": {
"name": "larry",
"age": 50
},
"60": {
"name": "curly",
"age": 60
}
}
Sorts a list into groups and returns a count for the number of objects in each group. Similar to groupBy
, but instead of returning a list of values, returns a count for the number of values in that group.
{{ [1,2,3,4,5] | countBy(function (num) {
return num % 2 == 0 ? 'even': 'odd';
}) }} => {"odd":3,"even":2}
Returns a shuffled copy of the list, using a version of the Fisher-Yates shuffle.
{{ [1,2,3,4,5,6] | shuffle }} => [5,2,3,6,1,4]
Produce a random sample from the list. Pass a number to return n random elements from the list. Otherwise a single random item will be returned.
{{ [1,2,3,4,5,6] | sample }} => one element
{{ [1,2,3,4,5,6] | sample(3) }} => there elements
Creates a real Array from the list (anything that can be iterated over). Useful for transmuting the arguments object.
{{ {"0":1,"1":2,"2":3,"3":4} | toArray }} => [1,2,3,4]
Return the number of values in the list.
{{ {"one":1,"two":2,"three":3} | size }} => 3
Note: All array functions will also work on the arguments object. However, Underscore functions are not designed to work on "sparse" arrays.
Returns the first element of an array. Passing n will return the first n elements of the array.
{{ [5,4,3,2,1] | first }} => 5
{{ [1,2] | first(0, [[1,2],[3,4]]) }} => 1
{{ [3,4] | first(1, [[1,2],[3,4]]) }} => 3
Returns everything but the last entry of the array. Especially useful on the arguments object. Pass n to exclude the last n elements from the result.
{{ [5,4,3,2,1] | initial }} => [5,4,3,2]
Returns the last element of an array. Passing n will return the last n elements of the array.
{{ [5,4,3,2,1] | last }} => 1
Returns the rest of the elements in an array. Pass an index to return the values of the array from that index onward.
{{ [5,4,3,2,1] | rest }} => [4,3,2,1]
Flattens a nested array (the nesting can be to any depth). If you pass shallow, the array will only be flattened a single level.
{{ [1,[2],[3,[[4]]]] | flatten }} => [1,2,3,4]
{{ [1,[2],[3,[[4]]]] | flatten(true) }} => [1,2,3,[[4]]]
Returns a copy of the array with all instances of the values removed.
{{ [1,2,1,0,3,1,4] | without(0, 1) }} => [2,3,4]
Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.
{{ [1,2,3] | union([101,2,1,10], [2,1]) }} => [1,2,3,101,10]
Computes the list of values that are the intersection of all the arrays. Each value in the result is present in each of the arrays.
{{ [1,2,3] | intersection([101,2,1,10], [2,1]) }} => [1,2]
Similar to without, but returns the values from array that are not present in the other arrays.
{{ [1,2,3,4,5] | difference([5,2,10]) }} => [1,3,4]
Produces a duplicate-free version of the array, using === to test object equality. In particular only the first occurence of each value is kept. If you know in advance that the array is sorted, passing true for isSorted will run a much faster algorithm. If you want to compute unique items based on a transformation, pass an iteratee function.
{{ [1,2,1,4,1,3] | uniq }} => [1,2,4,3]
Joins the elements of an array with the character passed as the parameter. The result is a single string.
{{ ['a','b','c'] | join('-') }} => 'a-b-c'
Reverse an array or a string.
{{ 'abc' | reverse }} => 'cba'
{{ [1,2,3] | reverse }} => [3,2,1]
Concatenates an array into another one.
{{ [1,2,3] | concat([4,5,6]) }} => [1,2,3,4,5,6]
{{ 'ab-cd' | replace('-', '') }} => 'abcd'
{{ 'javascript' | substr(0, 4) }} => 'java'
{{ 'javascript' | substring(0,2) }} => 'ja'
Appends characters to a string.
{{ 'sky' | append('.jpg') }} => 'sky.jpg'
Prepends characters to a string.
{{ 'world' | prepend('hello ') }} => 'hello world'
Converts a string into CamelCase.
{{ "some_else" | camelcase }} => "SomeElse"
{{ "some-else" | camelcase }} => "SomeElse"
Truncate text to a specified length.
{{ 'this is a big city!' | truncate(10, '...') }} => 'this is a ...'
The split filter takes on a substring as a parameter.The substring is used as a delimiter to divide a string into an array.
{{ 'a-b-c-d' | split('-') }} => [a,b,c,d]
Strips tabs, spaces, and newlines (all whitespace) from the left or right or both side of a string.which depends on second argument.
{{ ' some spaces ' | trim }} => 'some spaces'
{{ ' some spaces ' | trimLeft }} => 'some spaces '
{{ ' some spaces ' | trimRight }} => ' some spaces'
Test if a string match a pattern.
{{ "http://vuejs.org" | test("^http") }} => true
// second param is regExp flag
{{ "VUE" | test("vue", "i") }} => true
Pad a string on left.
{{ 'abc' | leftPad(5, '*') }} => '**abc'
Pad a string on right.
{{ 'abc' | rightPad(5, '*') }} => 'abc**'
Repeat a string n times.
{{ 'abc' | repeat(3) }} => 'abcabcabc'
{{ 'abc' | repeat('3') }} => 'abcabcabc'
{{ 'abc' | repeat(0) }} => ''
{{ 'abc' | repeat }} => ''
Lowercase a string.
{{ 'Vue' | lowercase }} => 'vue'
Uppercase a string.
{{ 'Vue' | uppercase }} => 'VUE'
Replace new lines by <br/>
tags. This returns a string conainting html tag so in order
to prevent vue from escaping the tags special rendering is needed: {{{ triple handlebars }}}
in Vue 1.0, v-html
with direct filter function in Vue 2.0
// Vue 1.0
<p> {{{ text | nl2br }}} </p>
// Vue 2.0
<p v-html="$options.filters.nl2br(text)"></p>
Retrieve all the names of the object's own enumerable properties.
{{ {"one":1,"two":2,"three":3} | keys }} => ["one","two","three"]
Retrieve all the names of object's own and inherited properties.
{{ {"name":"Moe"} | allKeys }} => ["name","silly"]
Return all of the values of the object's own properties.
{{ {"one":1,"two":2,"three":3} | values }} => [1,2,3]
Convert an object into a list of [key, value]
pairs. The opposite of object.
{{ {"one":1,"two":2,"three":3} | pairs }} => [["one",1],["two",2],["three",3]]
Returns a copy of the object where the keys have become the values and the values the keys. For this to work, all of your object's values should be unique and string serializable.
{{ {
"Moe": "Moses",
"Larry": "Louis",
"Curly": "Jerome"
} | invert }} =>
{
"Moses": "Moe",
"Louis": "Larry",
"Jerome": "Curly"
}
Shallowly copy all of the properties in the source objects over to the destination object, and return the destination object. Any nested objects or arrays will be copied by reference, not duplicated. It's in-order, so the last source will override properties of the same name in previous arguments.
{{ {"name":"moe"} | extend({"age":50}) }} => {"name":"moe","age":50}
Return a copy of the object, filtered to only have values for the whitelisted keys (or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.
{{ {"name":"moe","age":50,"userid":"moe1"} | pick("name", "age") }} => {"name":"moe","age":50}
{{ {"name":"moe","age":50,"userid":"moe1"} | pick(function (value, key, object) {
return typeof value === 'number'
}) }} => {"age":50}
Return a copy of the object, filtered to omit the blacklisted keys (or array of keys). Alternatively accepts a predicate indicating which keys to omit.
{{ {"name":"moe","age":50,"userid":"moe1"} | omit("userid") }} => {"name":"moe","age":50}
{{ {"name":"moe","age":50,"userid":"moe1"} | omit(function (value, key, object) {
return typeof value === 'number'
}) }} => {"name":"moe","userid":"moe1"}
Returns object after filling in its undefined
properties with the first value present in the following list of defaults objects.
{{ {"flavor":"chocolate"} | defaults({"flavor":"vanilla","sprinkles":"lots"}) }} => {"flavor":"chocolate","sprinkles":"lots"}
Does the object contain the given key? Identical to object.hasOwnProperty(key)
, but uses a safe reference to the hasOwnProperty
function, in case it's been overridden accidentally.
{{ {"a":1,"b":2,"c":3} | has("b") }} => true
abs
,acos
,asin
,atan
,atan2
,ceil
,cos
,exp
,floor
,log
,pow
,round
,sin
,sqrt
,tan
{{ -1.2 | abs }} => 1.2
{{ 1 | acos }} => 0
{{ 1.3 | ceil }} => 2
{{ 3 | pow(2) }} => 9 i.e: Math.pow(3,2)
Get sum of all values in an array.
{{ [1,2,3] | sum }} => 6
you can give an option argument as initial value
{{ [1,2,3] | sum(10) }} = 16
Return mean value of a array.
{{ [1,2,3,4] | mean }} => 2.5
Returns the minimum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. Infinity is returned if list is empty, so an isEmpty guard may be required. Non-numerical values in list will be ignored.
{{ [10,5,100,2,1000] | min }} => 2
Returns the maximum value in list. If an iteratee function is provided, it will be used on each value to generate the criterion by which the value is ranked. -Infinity is returned if list is empty, so an isEmpty guard may be required. Non-numerical values in list will be ignored.
{{ [{
"name":"moe","age":40
},{
"name":"larry","age":50
},{
"name":"curly","age":60
}] | max(function (stooge){
return stooge.age;
}) }} => {"name":"curly","age":60}
Adds a number to an output.
{{ 10 | plus(2) }} => 12
Subtracts a number from an output.
{{ 12 | minus(2) }} => 10
Multiplies an output by a number.
{{ 10 | multiply(2) }} => 20
Divides an output by a number
{{ 10 | divide(4) }} => 2.5
Divides an output by a number and returns the remainder.
{{ 10 | mod(3) }} => 1
{{ 3.1415926 | toFixed(4) }} => "3.1415"
{{ 3.1415926 | toPrecision(3) }} => "3.14"
{{ 1 | toPrecision(3) }} => "1.00"
Escapes a string for insertion into HTML, replacing &
, <
, >
, "
, ```, and '
characters.
{{ "Curly, Larry & Moe" | escape }} => "Curly, Larry & Moe"
The opposite of escape, replaces &
, <
, >
, "
, `
and '
with their unescaped counterparts.
{{ "Curly, Larry & Moe" | unescape }} => "Curly, Larry & Moe"
If the value of the named property is a function then invoke it with the object as context; otherwise, return it. If a default value is provided and the property doesn't exist or is undefined then the default will be returned. If defaultValue
is a function its result will be returned.
{{ {"cheese":"crumpets"} | result("cheese") }} => "crumpets"
{{ {"cheese":"crumpets"} | result("meat", "ham") }} => "ham"
Converts a timestamp into another date format.
{{ Date.now() | date('%T') }} => current time, format like: '13:34:36'
{{ 'Wed Jan 20 2016 13:34:36 GMT+0800' | date('%T') }} => '13:34:36'
{{ 1453268193752 | date('%Y-%m-%d') }} => '2016-01-20'
{{ new Date | date('%I:%M:%s %p') }} => '1:39:22 PM'
More date parameters are listed below:
Param | Explanation | Example |
---|---|---|
%a | Abbreviated weekday. | "%a" => "Sat" |
%A | Full weekday name. | "%A" => "Tuesday" |
%b | Abbreviated month name. | "%b" => "Jan" |
%B | Full month name | "%B" => "January" |
%c | Preferred local date and time representation | "%c" => "Tue Apr 22 11:16:09 2014" |
%d | Day of the month, zero-padded (01, 02, 03, etc.). | "%d" => "04" |
%-d | Day of the month, not zero-padded (1,2,3, etc.). | "%-d" => "4" |
%D | Formats the date (dd/mm/yy). | "%D" => "04/22/14" |
%e | Day of the month, blank-padded ( 1, 2, 3, etc.). | "%e" => "3" |
%F | Returns the date in ISO 8601 format (yyyy-mm-dd). | "%F" => "2014-04-22" |
%H | Hour of the day, 24-hour clock (00 - 23). | "%H" => "15" |
%I | Hour of the day, 12-hour clock (1 - 12). | "%I" => "7" |
%j | Day of the year (001 - 366). | "%j" => "245" |
%k | Hour of the day, 24-hour clock (1 - 24). | "%k" => "14" |
%m | Month of the year (01 - 12). | "%m" => "04" |
%M | Minute of the hour (00 - 59). | "%M" => "53" |
%p | Meridian indicator (AM/PM). | "%p" => "PM" |
%r | 12-hour time (%I:%M:%S %p) | "%r" => "03:20:07 PM" |
%R | 24-hour time (%H:%M) | "%R" => "15:21" |
%T | 24-hour time (%H:%M:%S) | "%T" => "15:22:13" |
%U | The number of the week in the current year, starting with the first Sunday as the first day of the first week. | "%U" => "16" |
%W | The number of the week in the current year, starting with the first Monday as the first day of the first week. | "%W" => "16" |
%w | Day of the week (0 - 6, with Sunday being 0). | "%w" => "2" |
%x | Preferred representation for the date alone, no time. (mm/dd/yy). | "%x" => "04/22/14" |
%X | Preferred representation for the time. (hh:mm:ss). | "%X" => "13:17:24" |
%y | Year without a century (00.99). | "%y" => "14" |
%Y | Year with a century. | "%Y" => "2014" |
Get a property inside an Object
user = {
contact: {
tel: "187xxxx0001"
}
}
{{ user | get('contact.tel') }} => "187xxxx0001"
MIT