diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ad2ccf43..ef8c51bd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ - Removed: `statinamic/lib/enhance-collection` do not add siblings by default. You will need to pass `{ addSiblingReferences: true }` in the options to get next and previous references to collection items. +- Added: `statinamic/lib/enhance-collection` can now filter keys using a RegExp. - Added: when `--production` is used, `process.env.NODE_ENV` is automatically set to `production`. diff --git a/src/enhance-collection/__tests__/index.js b/src/enhance-collection/__tests__/index.js new file mode 100644 index 000000000..91afd7855 --- /dev/null +++ b/src/enhance-collection/__tests__/index.js @@ -0,0 +1,42 @@ +import tape from "tape" + +import enhanceCollection from ".." + +tape("statinamic/lib/enhance-collection", (test) => { + + const collec = [ + { k: "ey" }, + { k: "ay" }, + { k: "ei" }, + { k: "eye" }, + ] + + test.deepEqual( + enhanceCollection( + collec, + { + filter: { k: "ey" }, + } + ), + [ + { k: "ey" }, + ], + "should filter by object { key: string }" + ) + + test.deepEqual( + enhanceCollection( + collec, + { + filter: { k: /y$/ }, + } + ), + [ + { k: "ey" }, + { k: "ay" }, + ], + "should filter by object { key: regexp }" + ) + + test.end() +}) diff --git a/src/enhance-collection/index.js b/src/enhance-collection/index.js index da25eef06..96db41bec 100644 --- a/src/enhance-collection/index.js +++ b/src/enhance-collection/index.js @@ -44,7 +44,17 @@ export function filter(collection, filters) { const keys = Object.keys(filter) if ( keys.reduce( - (acc, key) => acc && item[key] === filter[key], + (acc, key) => acc && ( + ( + typeof filter[key] === "string" && + item[key] === filter[key] + ) + || + ( + filter[key] instanceof RegExp && + item[key].match(filter[key]) + ) + ), true ) ) {