2017-07-18 11 views
0

自分のコントローラーで異なるリストでこれを15回以上実行しています。そのようなオブジェクトのフィルタリングと値の設定を行う標準機能

setTick(vm.property, vm.propertyList); 

か何かを:私は好きで、それを呼び出すよう

var selected = vm.countryList.filter(function(obj){return obj.id == vm.country}) 
if (selected.length) { selected[0].ticked = true } 

var selected = vm.languageList.filter(function(obj){return obj.id == vm.language}) 
if (selected.length) { selected[0].ticked = true } 

var selected = vm.propertyList.filter(function(obj){return obj.id == vm.property}) 
if (selected.length) { selected[0].ticked = true } 

気の利いた小さな関数を記述することは可能でしょうか?

+0

はい、可能であれば、 'setTick'の実装がどのように動作するのか見てみましたか? – Agalo

+0

それはちょうど私が繰り返し書く2つの行のようにする必要があります:) – torbenrudgaard

答えて

1

次の操作を実行できます。

function setTick(propertyName) { 
    var selected = vm[propertyName + 'List'].filter(function(obj) {return obj.id == vm[propertyName]}); 
    if (selected.length) { selected[0].ticked = true } 
} 

、そのような使用に:

ES6で
setTick('language'); 
setTick('country'); 

const setTick = (propertyName) => { 
    const selected = vm[`${propertyName}List`].filter(obj => obj.id == vm[propertyName]); 
    if (selected.hasOwnProperty('length')) 
    selected[0].ticked = true 
} 

// You can also use it like the following : 

['language', 'country', 'property'].forEach(propName => setTick(propName)); 

はそれが役に立てば幸い、
よろしく

+0

Boehmはあなたの天才ハッカーの何かか何ですか? Hehehは、私のコントローラから200行分のコードを削除します.-D Thanks !!!本当に涼しいES6バージョンbtw、私はあなたが何をしているのか理解しています:-D – torbenrudgaard

関連する問題