在Javascript中数组对象(json)里元素相同的操作
1、数组对象元素相同,分组显示
let arry = [ { expensedate: '2018/09/29', amount: 1, type: '交通费' }, { expensedate: '2018/08/19', amount: 2.5, type: '补贴费' }, { expensedate: '2018/09/29', amount: 6.3, type: '住宿费' }, { expensedate: '2018/01/19', amount: 18.5, type: '采购经费' }, { expensedate: '2018/09/22', amount: 8.4, type: '活动经费' }, { expensedate: '2018/09/29', amount: 7.9, type: '材料打印费' } ] let items = []; let datelist = {}; for (let i = 0; i < arry.length; i++) { let element = arry[i]; if (!datelist[element.expensedate]) { items.push({ expensedate: element.expensedate, subitems: [element] }) datelist[element.expensedate] = element; } else { for (let j = 0; j < items.length; j++) { let subment = items[j]; if (subment.expensedate == element.expensedate) { subment.subitems.push(element) } } } } console.log(items);
2、数组对象元素相同,汇总显示
let arrys = [ { expensedate: '2018/09/29', amount: 1, type: '交通费' }, { expensedate: '2018/08/19', amount: 2.5, type: '补贴费' }, { expensedate: '2018/09/29', amount: 6.3, type: '交通费' }, { expensedate: '2018/01/08', amount: 18.5, type: '采购经费' }, { expensedate: '2018/09/22', amount: 8.4, type: '活动经费' }, { expensedate: '2018/09/29', amount: 7.9, type: '交通费' } ] let otheritems = []; let list = {}; for (let i = 0; i < arrys.length; i++) { let element = arry[i].expensedate; if (list[element]) { list[element].expensedate = list[element].expensedate; list[element].amount = list[element].amount + arrys[i].amount; } else { list[element] = {}; list[element].expensedate = arrys[i].expensedate; list[element].amount = arrys[i].amount; } list[element].type = arrys[i].type; } //对象转数组 for (var i in list) { otheritems.push(list[i]) } console.log(otheritems)