简体   繁体   中英

JS best practice List of Objects vs Array vs Value-Pair

I am working on a learning project (basically I am building a web site based on Node-Express to learn Node-Express). I need to make a 'menu', and I am struggling finding the best way to represent it in JSON (and then to use in a HTML table). the options I thought of are:

{"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} ]}

I found a way to process all the above but I would like to understand which one is the best option for my scenario (and possibly why the others are not).

 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> 

I would opt for this:-

var menu = {"coffee": 2.00, "juice": 3.50, "smoothy": 4.00}

I have many reasons :-

  • Easy to maintain (as simple key-value pair)
  • Easy to Iterate over
  • Easy for retrieve value according to item name
  • Easy for filtering (like you want to filter according to price may be simple or may be price range)

The third one is more semantic and friendly. you can easily iterate through them and use item for other operations like, say if (item == something) , and it looks more readable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM