× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Dynamically generate objects when possible

Sultan B. Shakir
Apr 01, 2016
<h2>Instead of writing (50 lines of code):</h2> <pre><code class="language-javascript">var baseValue = { "January ": { "salesrev": 0, "salesprofit": 2 }, "February": { "salesrev": 0, "salesprofit": 0 }, "March": { "salesrev": 0, "salesprofit": 0 }, "April": { "salesrev": 0, "salesprofit": 0 }, "May": { "salesrev": 0, "salesprofit": 0 }, "June": { "salesrev": 0, "salesprofit": 0 }, "July": { "salesrev": 0, "salesprofit": 0 }, "August": { "salesrev": 0, "salesprofit": 0 }, "September": { "salesrev": 0, "salesprofit": 0 }, "October": { "salesrev": 0, "salesprofit": 0 }, "November": { "salesrev": 0, "salesprofit": 0 }, "December": { "salesrev": 0, "salesprofit": 0 } };</code></pre> <p><img><img style="height:15px; width:15px"></p> <h2>Dynamically generate your object (11 lines of code):</h2> <pre><code class="language-javascript">//List of Months var monthsList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; // object we are dynamically creating below var baseValue = {}; var setBaseRevProfit = function(monthsList) { for (var i = 0; i &lt; monthsList.length; i++) { baseValue[monthsList[i]] = { salesrev: 0, salesprofit: 0 } } } setBaseRevProfit(monthsList);</code></pre> <p> </p>
comments powered by Disqus