如何将类型为对象数组的 json 集合 arr 中的 price 属性累加计算,生成 obj_1 或 arr_1 ?
用原生 js 的 for 循环 或 underscore 如何实现?
var arr = [ { id:1, name: '商户1', price: 400 }, { id:3, name: '商户3', price: 200 }, { id:2, name: '商户2', price: 100 }, { id:1, name: '商户1', price: 200 }, { id:4, name: '商户4', price: 800 }, { id:2, name: '商户2', price: 600 }, { id:1, name: '商户1', price: 400 } ]; var obj_1 = { 1: { name: '商户1', price: 1000 }, 2: { name: '商户2', price: 700 }, 3: { name: '商户3', price: 200 }, 4: { name: '商户4', price: 800 }, } var arr_1 = [ { id:1, name: '商户1', price: 1000 }, { id:2, name: '商户2', price: 700 }, { id:3, name: '商户3', price: 200 }, { id:4, name: '商户4', price: 800 }, ];
三叔2016-11-10 14:47:05
var arr = [ { id:1, name: '商户1', price: 400 }, { id:3, name: '商户3', price: 200 }, { id:2, name: '商户2', price: 100 }, { id:1, name: '商户1', price: 200 }, { id:4, name: '商户4', price: 800 }, { id:2, name: '商户2', price: 600 }, { id:1, name: '商户1', price: 400 } ]; var count = 0 var arr_1 = [] var obj_1 = [] for(var i=0;i
返事0
欧阳克2016-11-10 14:46:44
var sum = 0,arr_1=[...],arr_2=[...],arr_3=[...]; function counter(obj){ obj.forEach(function(item){ sum+=item.price; }) } counter(arr_1); counter(arr_2); counter(arr_3);
三叔2016-11-10 14:46:28
试试这个
var reduced = arr.reduce(function(p, item) { if (p[item.id]) { p[item.id].price += item.price; } else { p[item.id] = {name: item.name, price: item.price}; } return p; }, {}); console.log(reduced);