[英]Group array of objects based on the object's key/value-pair which is in an array
[英]JS best practice List of Objects vs Array vs Value-Pair
我正在從事一個學習項目(基本上我正在基於Node-Express構建一個網站來學習Node-Express)。 我需要做一個“菜單”,我正在努力尋找以JSON表示它(然后在HTML表中使用)的最佳方法。 我想到的選項是:
{"menu" : [{"coffee": 2.00}, {"juice": 3.50}, {"smoothy": 4.00}]}
{"menu" : {"coffee": 2.00, "juice": 3.50, "smoothy": 4.00}}
{"menu" : [{"item": "coffee", "price": 2.00}, {"item": "juice", "price": 3.50}, {"item": "smooth", "price": 4.00} ]}
我找到了一種處理上述所有問題的方法,但是我想了解哪種方法最適合我的情況(以及其他原因為什么不可行)。
var menu = {"coffee": 2.00, "juice": 3.50, "smoothy": 4.00} $(function() { //FILTER example var filter = _.pick(menu, function(num){ return num % 2 == 0; }); console.log(filter) })
<script src="http://underscorejs.org/underscore.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
我會選擇:
var menu = {"coffee": 2.00, "juice": 3.50, "smoothy": 4.00}
我有很多理由:
第三個是語義和友好的。 您可以輕松地遍歷它們,並將item
用於其他操作,例如if (item == something)
,它看起來更具可讀性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.