曹え 5811 发布于:2021-12-30 10:50:01
平时工作中会经常遇到数据处理,其中数组合并处理也会经常遇到,下面就是数组相同项合并的一种方式:
1.首先由原始的数组arr数据,
2.然后创建一个map空对象和一个dest空数组,通过判断map中是否含有某项来判断数组dest是否添加数据,
3.然后再判断相同项和已有的dest数组内容比较合并;
下面的是对比 id ,也可以对比 name 等字段
<script type="text/javascript" src="js/jquery.min.js"></script> <script> $(function(){ var arr = [ {"id":"1","name":"张三","value":"1245"}, {"id":"1","name":"张三","value":"1360"}, {"id":"2","name":"李四","value":"1120"}, {"id":"2","name":"李四","value":"1362"}, {"id":"2","name":"李四","value":"1008"}, {"id":"3","name":"王五","value":"1360"}, {"id":"4","name":"赵六","value":"1986"}, {"id":"4","name":"赵六","value":"1240"} ]; var map = {},dest = []; for(var i = 0; i < arr.length; i++){ var ai = arr[i]; if(!map[ai.id]){ dest.push({ id: ai.id, name: ai.name, value: ai.value }); map[ai.id] = ai; }else{ for(var j = 0; j < dest.length; j++){ var dj = dest[j]; if(dj.id == ai.id){ dj.value=(parseFloat(dj.value) + parseFloat(ai.value)).toString(); break; } } } }; console.log(dest); }) </script>
登录后可以留言提问!
微信扫码登录