2017-08-21 19 views
0

我對打印稿中評估用戶自定義條件有疑問。 就我而言:我有一個UI和一個代碼(我的模型)。 我的示例數據對象的樣子:如何使用打字稿中的用戶自定義條件進行評估

let data = [ 
    { 
     id: 0, 
     type: vw 
     eos, 
     costs: 23000 
    }, 
    { 
     id: 1, 
     type: ford 
     van, 
     costs: 14000 
    }, 
    { 
     id: 2, 
     type: nissan 
     sumara, 
     costs: 15000 
    }, 
    { 
     id: 3, 
     type: honda 
     civic, 
     costs: 17500 
    } 
] 

那麼,在UI用戶得到了一個輸入文本字段,他應該作出請求給IM所有汽車這是紅色的,例如。用戶輸入將如下所示: 「成本< = 15000」,現在應該將此字符串用作條件,以便我返回以下結果:ids:1,2。

任何人的想法如何,我可以使用requeststring從用戶的條件,如?:

data.forEach(object => { 
    if(usercondition) //an idea how to solve this? 
    { 
     this.result.push(object); 
    }}); 

感謝您的任何建議!

+0

你嘗試過什麼嗎? – Chris

+0

爲什麼使用foreach?爲什麼不[filter](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)? – k0pernikus

回答

0

基本代碼看起來像這樣。但請注意:使用過濾器而不是從用戶處獲得輸入,因爲您無法限制用戶可以在文本框中輸入的內容。我不確定在複雜情況下你將如何實現這一目標。

usercondition將保持條件,比如cost < 15000。該值將由文本輸入設置。

addItem(usercondition: any) { 

this.data.forEach(obj => 
{ 
    var strcondition = 'obj.' + usercondition; 
    // console.log(strcondition) will print obj.cost < 15000 

    if (eval(strcondition)) // evaluate the expression and check the condition 
    { 
     this.result.push(object); 
    } 
    }); 
} 
相關問題