计算特定键

时间:2016-08-25 20:13:51

标签: javascript object lodash

我有这个对象:

"formData": {
    "Total": "60.00",
    "listTable": [],
    "tr0_CC": "KFC",
    "tr0_amount": "10.00",
    "tr1_CC": "SUB",
    "tr1_amount": "20.00",
    "tr2_CC": "WEN",
    "tr2_amount": "30.00"
}

如何只使用native或lodash计算键tr#_amount?在上面的例子中,我应该得到3

1 个答案:

答案 0 :(得分:1)

这里有一些标准(ES6)Javascript:



a = {"formData": {
    "Total": "60.00",
    "listTable": [],
    "tr0_CC": "KFC",
    "tr0_amount": "10.00",
    "tr1_CC": "SUB",
    "tr1_amount": "20.00",
    "tr2_CC": "WEN",
    "tr2_amount": "30.00"
}};

console.log(Object.keys(a.formData).filter(t => t.match(/tr\d+_amount/)).length);