JavaScript数组中的循环增加办法

一、JS对象数组各个值相加

var dataList = [
    { id: 1, price: 5.5, amount: 3 },
    { id: 2, price: 1.5, amount: 5 },
    { id: 3, price: 3.5, amount: 8 },
    { id: 4, price: 5.5, amount: 2 },
    { id: 5, price: 0.5, amount: 7 },
    { id: 6, price: 1.5, amount: 4 },
    { id: 7, price: 6.5, amount: 9 }
];
function arrOperate (allData) {
    let newArr = [], obj = {};
    allData.forEach(item => {
        for (let key in item) {
            let value = item[key];
            key in obj ? (obj[key] += value) : (obj[key] = value);
        }
    });
    for (let i in obj) {
        let o = {};
        o[i] = obj[i];
        newArr.push(o);
    };
    console.log(newArr); // [ { id: 28 }, { price: 24.5 }, { amount: 38 } ]
}
arrOperate(dataList);

二、JS对象数组key值相等value相加

let arr = [{ "语文": 100, "数学": 100 }, 
           { "语文": 100, "数学": 100 }, 
           { "语文": 100, "数学": 100, "英语": 100 }, 
           { "语文": 100, "数学": 100, "物理": 100 }, 
           { "英语": 100, "化学": 100 }, ];
let newArr = [], obj = {};
arr.forEach(item => {
    for(let key in item) {
        let value = item[key];
        key in obj ? (obj[key] += value) : (obj[key] = value)
    }
});
//遍历对象转为数组
for(let i in obj) {
    let o = {};
    o[i] = obj[i];
    newArr.push(o)
}
console.log(newArr); // [{语文:400},{数学:400},{英语:200},{物理:100},{化学:100}]

三、JS数组对象的去重和排序操作

// 合并相同价格(price)的数量(amount)并以价格从小到大排序
var dataList = [
    { id: 1, price: 5.5, amount: 3 },
    { id: 2, price: 1.5, amount: 5 },
    { id: 3, price: 3.5, amount: 8 },
    { id: 4, price: 5.5, amount: 2 },
    { id: 5, price: 0.5, amount: 7 },
    { id: 6, price: 1.5, amount: 4 },
    { id: 7, price: 6.5, amount: 9 }
];
// 排序方法
function compare(prop) {
    return function(a, b) {
        return a[prop] - b[prop]
    }
}
dataList.sort(compare('price'))
// 最终的数据
var newArray = []
// 空对象
var newObject = {}
// 重复的数据
var otherArray = []
// 利用对象访问属性的方法,判断对象中是否存在price
dataList.forEach(v => {
    if (!newObject[v.price]) {
        newObject[v.price] = true
        newArray.push(v)
    } else {
        otherArray.push(v)
    }
});
// 合并数量的操作
otherArray.forEach(v => {
    newArray.forEach(k => {
        if (v.price === k.price) {
            k.amount += v.amount
        }
    });
});
// [{"id":5,"price":0.5,"amount":7},{"id":2,"price":1.5,"amount":9}, {"id":3,"price":3.5,"amount":8},{"id":1,"price":5.5,"amount":5},{"id":7,"price":6.5,"amount":9}]
console.log(newArray);

四、js计算数组里的对象的某个值相同,其余值相加

let arry=[ {Code:'x',Quantity:1,ItemType:'normal'},
           {Code:'x',Quantity:2,ItemType:'normal'},
           {Code:'x',Quantity:5,ItemType:'normal'},
           {Code:'y',Quantity:1,ItemType:'spec'},
           {Code:'y',Quantity:2,ItemType:'spec'},
           {Code:'z',Quantity:1,ItemType:'normal'} ];
let newfood=[];
var temp = {};
for(var i in arry) {
    var key= arry[i].Code;
    if(temp[key]) {
        temp[key].Code = temp[key].Code ;
        temp[key].Quantity = temp[key].Quantity+ arry[i].Quantity;
    } else {
        temp[key] = {};
        temp[key].Code = arry[i].Code;
        temp[key].Quantity = arry[i].Quantity;
    }
    temp[key].ItemType= arry[i].ItemType; 
}
for(var k in temp){
    newfood.push(temp[k])
}
alert(JSON.stringify(newfood));
//[{"Code":"x","Quantity":8,"ItemType":"normal"},{"Code":"y","Quantity":3,"ItemType":"spec"},{"Code":"z","Quantity":1,"ItemType":"normal"}] 

五、js根据对象数组中某一属性值,合并相同项,并对某一属性累加处理

let data = [
    { code: 1001, name: '苹果', sl: 11 },
    { code: 1001, name: '苹果', sl: 11 },
    { code: 1001, name: '苹果', sl: 11 },
    { code: 1001, name: '苹果', sl: 11 },
    { code: 1002, name: '西瓜', sl: 11 },
    { code: 1002, name: '西瓜', sl: 15 },
    { code: 1003, name: '梨', sl: 15 },
    { code: 1003, name: '梨', sl: 15 },
];
// 第一种:根据对象key的唯一性,累加sl值
let item = {};
for (let i = 0; i < data.length; i++) {
    item[data[i].code] = ~~item[data[i].code] + data[i].sl
}
console.log(item); // 结果: {1001: 44, 1002: 26, 1003: 30}

//第二种:根据reduce遍历累加,得到数组
let newArray = data.reduce((total, cur, index) => {
    let hasValue = total.findIndex(current => { return current.code === cur.code});
    hasValue === -1 && total.push(cur);
    hasValue !== -1 && (total[hasValue].sl = total[hasValue].sl + cur.sl);
    return total;
}, []);
console.log(newArray); // 结果: [{code: 1001, name: "苹果", sl: 44}, {code: 1002, name: "西瓜", sl: 26}, {code: 1003, name: "梨", sl: 30}]

六、又一个循环添加

var arry= [
    {key:'a',value:2},
    {key:'a',value:2},
	{key:'a',value:2},
	{key:'b',value:8}
]

// 第一种
let target = [];
let keysArr =[...new Set( arry.map(item=>item.key))]  ;
keysArr.forEach(item=>{
	const  arr = arry.filter(keys=>keys.key == item);
	const sum = arr.reduce((a,b)=>a+b.value,0)
	target.push({
		key:item,
		value:sum
	})
})
console.log(target)

// 第二种方式
var newArr = [...arry.reduce((m, x) => m.set(x.key, (m.get(x.key) || 0) + x.value), new Map())].map(([key, value]) => ({ key, value }))
console.log(newArr)

// 第三种方式
function keyPlusValue(arr) {
	const result = arr.reduce((obj, item) => {
		if (!obj[item.key]) {
			 obj[item.key] = 0
		}
		obj[item.key] += item.value
		return obj
	}, {})
	return Object.keys(result).map(key => ({key: key, value: result[key]}))
}
console.log(keyPlusValue(arry))


// 第四种方式
let newArr = arry.reduce((resp, obj)=> {
	var originObj = resp.find(item => item.key === obj.key);
	if (originObj) {
		originObj.value+= obj.value;
	} else {
		resp.push(obj)
	}
	return resp;
}, [])
console.log(newArr)

 结果:

七、

//问题一:js中根据数组对象中的相同id值进行合并,并将name值合并,并且用逗号隔开返回新的数组对象
let dataArr = [
	{ id:1, name:"A", score:10 },
	{ id:2, name:"B", score:20 },
	{ id:1, name:"C", score:30 },
	{ id:2, name:"D", score:40 }
];
//将dataArr赋值给beforeData  也可直接操作dataArr
var beforeData = dataArr;      
let tempArr = [];
let afterData = [];//新数组
for (let i = 0; i < beforeData.length; i++) {
	if (tempArr.indexOf(beforeData[i].id) === -1) {
		afterData.push({
			id: beforeData[i].id,
			score: beforeData[i].score,
			name: [beforeData[i].name],
		});
		tempArr.push(beforeData[i].id);
	} else {
		for (let j = 0; j < afterData.length; j++) {
			if (afterData[j].id == beforeData[i].id) {
				afterData[j].name.push(beforeData[i].name);
				break;
			}
		}
	}
}
//循环afterData并且合并name值用逗号隔开
afterData.map((item) => {
	item.name= item.name.join(",");
});
console.log(afterData);

 

你可能感兴趣的:(JavaScript,javascript,前端,开发语言)