私が反応するようにngのから移動する過程で自分自身にこのように多くの時間を求めてきましたし、これは(キーを解析するlodashを使用します。値のペア)ソリューションであります私のために最善を働いてしまった:
import _ from 'lodash';
function escapeRegexCharacters(str) {
//make sure our term won't cause the regex to evaluate it partially
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
var filterHelper = {
filterObjectArrayByTerm: function(arr, term) {
//make sure the term doesn't make regex not do what we want
const escapedTerm = escapeRegexCharacters(term.trim());
//make the regex do what we want
const regEx = new RegExp (escapedTerm, 'ig');
//if the term is blank or has no value, return the object array unfiltered
if(escapedTerm === '' || escapedTerm === null || escapedTerm === undefined) {
return arr;
}
//iterate over each object in the array and create a map
return arr.map((obj) => {
//if any value in a key:value pair matches the term regex
if(Object.values(obj).filter((value) => regEx.test(value)).length > 0){
//return the object in the map
return obj;
} else {
//otherwise put the object in as null so it doesn't display
return null;
}
});
},
//most similar to ng-repeat:ng-filter in ng
filterObjectArrayByKeyThenTerm: function(arr, key, term) {
//make sure the terms don't make regex not do what we want
const escapedKey = escapeRegexCharacters(key.trim());
const escapedTerm = escapeRegexCharacters(term.trim());
//make the regex do what we want
const keyRegex = new RegExp (escapedKey, 'ig');
const termRegex = new RegExp (escapedTerm, 'ig');
//if the key or term value is blank or has no value, return array
if(escapedTerm === '' || escapedTerm === null || escapedTerm === undefined || escapedKey === '' || escapedKey === null || escapedKey === undefined) {
return arr;
}
//iterate over each object in the aray passed in and create a map
return arr.map((obj) => {
//mapped object hasn't matched the regex yet
let match = false;
//can't .map() over key:value pairs, so _.each
_.each(obj, (value, key) => {
//if the key and value match the regex
if(keyRegex.test(key) && termRegex.test(value)) {
//set match to true
match = true;
}
});
//if match was set to true
if(match){
//return the object in the map
console.log('success');
return obj;
} else {
//otherwise put the object in as null so it doesn't display
return null;
}
});
},
};
module.exports = filterHelper;
どこか年のアプリの構造で、そのファイルを持っていたら、あなたは
を呼び出すことによって、これらの機能のいずれかを使用することができます
import 'filterHelper' from '/path/to/filterHelper/filterhelper.js'
ng-repeat:ng-filter in を使用した場合は、どのようなコンポーネントでも、オブジェクトの配列を任意の値またはキー:値のペアでフィルタリングできます。
実例(term、key、arrが状態値などに設定されているなど)が好きな場合は教えてください。
私は、Angularのような本格的なフレームワークではなく、ReactJSが間違いなくライブラリであることを知りました。あなたが念入りに取ったものをコード化する必要がある時があります。これは間違いなく悪いことではありません。ただの観察。いずれにしても、これを達成するためのnpmには良いものがあると確信しています。インスピレーションのためにhttps://react.rocks/tag/Filterをチェックしてください。 –
私はJohn F. Reactと100%合意していますが、モノリシックなフレームワークではなくユーザーランドのライブラリです。それは幻想的に1つのことを行い、素晴らしいコミュニティを起動します。 – Urasquirrel