将js对象数组按照相同属性重新组合成一个新的对象数组
查询出来的数据是这样的:
目前的数据是这样的,每个品牌都有对应7个月份的折扣数据,但是我想获得的数据效果是这样的 :
目前想了好久,唯一想到的方法就是将查出来的数据,重新组合成一个包含各品牌及其每个月折扣的对象数组
var brandDiscountArr = [] // 重新组合的品牌数据数组 var discountObj = {} //各品牌每月销量对象 var brandNameSet = new Set(); // 所有品牌 this.brandDiscountList.forEach(x => brandNameSet.add(x.brandName)); // 利用set去重获取数组中的所有品牌名称 for (let s of brandNameSet.keys()) { // 先遍历每个品牌 discountObj = {} this.brandDiscountList.forEach(item => { // 在遍历所有数据,按照品牌名称组建数组 if(item.brandName === s){ discountObj.brandName = item.brandName if(item.month === '1月'){ discountObj.Jan = item.discountRate } if(item.month === '2月'){ discountObj.Feb = item.discountRate } if(item.month === '3月'){ discountObj.Mar = item.discountRate } if(item.month === '4月'){ discountObj.Apr = item.discountRate } if(item.month === '5月'){ discountObj.May = item.discountRate } if(item.month === '6月'){ discountObj.Jun = item.discountRate } if(item.month === '7月'){ discountObj.Jul = item.discountRate } } }) brandDiscountArr.push(discountObj) } this.brandDiscountArr = brandDiscountArr
最终得到的数组效果如下
js对象数组根据某个共同字段重新分组
希望的是将下面的对象数组:
[ {"id":"1001","name":"值1","value":"111"}, {"id":"1001","name":"值1","value":"11111"}, {"id":"1002","name":"值2","value":"25462"}, {"id":"1002","name":"值2","value":"23131"}, {"id":"1002","name":"值2","value":"2315432"}, {"id":"1003","name":"值3","value":"333333"} ]
根据相同name字段分组,转换成下面这种形式:
[ { "id": "1001", "name": "值1", "data": [ {"id": "1001", "brandName": "值1", "value": "111"}, { "id": "1001", "brandName": "值1", "value": "11111"} ] }, { "id": "1002", "name": "值2", "data": [ { "id": "1002", "brandName": "值2", "value": "25462" }, { "id": "1002", "brandName": "值2", "value": "23131"}, {"id": "1002", "brandName": "值2","value": "2315432" } ] }, { "id": "1003", "name": "值3", "data": [ {"id": "1003", "brandName": "值3", "value": "333333" } ] } ]
做法:
var arr = [ {"id":"1001","brandName":"值1","value":"111"}, {"id":"1001","brandName":"值1","value":"11111"}, {"id":"1002","brandName":"值2","value":"25462"}, {"id":"1002","brandName":"值2","value":"23131"}, {"id":"1002","brandName":"值2","value":"2315432"}, {"id":"1003","brandName":"值3","value":"333333"} ] var map = {} var dest = [] for(var i = 0; i < this.budgetList.length; i++){ var ai = this.budgetList[i] if(!map[ai.brandName]){ dest.push({ id: ai.id, brandName: ai.brandName, data: [ai] }); map[ai.brandName] = ai }else{ for(var j = 0; j < dest.length; j++){ var dj = dest[j]; if(dj.brandName== ai.brandName){ dj.data.push(ai) break } } } } console.log(JSON.stringify(dest))
js两个数组对象根据属性相同的值合并
const a=[{ uid: 1, name: 'apple' },{ uid: 2, name: 'banana' }] const b=[{ uid: 1, unit: 'pcs' },{ uid: 2, unit: 'kg' }] // 期待的效果 c=[{ uid: 1, name: 'apple', unit: 'pcs', },{ uid: 2, name: 'banana', unit: 'kg', }] // 实现方法 a.map(el => { if(b.find(item => item.uid == el.uid) != null){ el.unit = b.find(item => item.uid == el.uid).unit } }) console.log(a)