1. 假如shopping_count对象里存放的是对inputs去重后的商品编码及数量,建立一个空的数组存放最终的商品信息,首先判断allItems里的商品编码在shopping_count是否存在,若存在则为1.allItems[j]对象赋一个count属性并赋值,用 allItems[j].count=值 就可以了,然后把allItems[j]放新的item_inputs数组里。
具体程序代码如下:
function get_item_inputs(shopping_count,allItems){ var item_inputs=[]; for(var j=0; j<allItems.length; j++){ if( allItems[j].barcode in shopping_count){ allItems[j].count=shopping_count[allItems[j].barcode]; item_inputs.push(allItems[j]); } } return item_inputs; }
2.为了编写简单,经常使用countBy()方法。
排序一个列表组成一个组,并且返回各组中的对象的数量的计数。类似groupBy,但不是返回列表的值,而是返回在该组中值的数目。
_.countBy([1, 2, 3, 4, 5], function(num) { return num % 2 == 0 ? 'even': 'odd'; }); 结果为:{odd: 3, even: 2}