双循环
ary.forEach(function(item,index){...}) forEach循环只能return结束本轮,不能结束整个
$.each(ary,function(index,item){...}) jq的each循环return true是结束本轮循环,return false是结束整个循环
<div id="app" v-cloak> <table style="width:700px;"> <tr v-for="(item,index) in list" :key="index"> <td style="width:40%">{{item.A.name}}</td> <td style="width:20%">——</td> <td style="width:40%">{{item.B.name}}</td> </tr> </table> </div> <script src="http://www.h5al.cn/js/vue2716.js"></script> <script src="http://www.h5al.cn/js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> var vm = new Vue({ el:"#app", data:{ list:[] }, created(){ this.getData() }, methods:{ getData(){ var self = this var ary11 = [ {A:{id: 1, name: 'abcd1'},B:{id: 2, name: '不要的efg1'},uid:1}, {A:{id: 3, name: 'abcd2'},B:{id: 4, name: '不要的efg2'},uid:2}, {A:{id: 5, name: 'abcd3'},B:{id: 6, name: '不要的efg3'},uid:3}, {A:{id: 7, name: 'abcd4'},B:{id: 8, name: '不要的efg4'},uid:4} ] var ary22 = [ {A:{id: 1, name: '不要的hijk1'},B:{id: 2, name: 'lmn1'},uid:1}, {A:{id: 3, name: '不要的hijk2'},B:{id: 4, name: 'lmn2'},uid:2}, {A:{id: 5, name: '不要的hijk3'},B:{id: 6, name: 'lmn3'},uid:3}, // {A:{id: 7, name: '不要的hijk4'},B:{id: 8, name: 'lmn4'},uid:4}, // {A:{id: 9, name: '不要的hijk5'},B:{id: 10, name: 'lmn5'},uid:5} ] //始终不要ary11的B数据和ary22的A数据 if(ary11.length > ary22.length){ //数组ary11比数组ary22多:ary11的A数据保留,B数据为ary22的B数据,不够的赋空 $.each(ary11,function(index,item){ item.B.name = '' $.each(ary22,function(ind,it){ var num = ind+1 if(item.uid == num){ item.B = it.B return false } }) }) self.list = ary11 }else{ //数组ary22比数组ary11多:ary11的A数据保留,B数据为ary22的B数据,不够的A数据赋空 $.each(ary22,function(index,item){ item.A.name = '' item.uid = index + 1 $.each(ary11,function(ind,it){ var num = ind+1 if(item.uid == num){ item.A = it.A return false } }) }) self.list = ary22 } } } }) </script>
//将两个数组ary1和ary2拼成一个数组,ary1第一项的对象与ary2第一项的对象合并,并且key重命名,如果ary2为空,则生成空值 var ary1 = [ {id: 1, name: 'abcd1',type:1}, {id: 2, name: 'abcd2',type:1}, {id: 3, name: 'abcd3',type:1} ] var ary2 = [ {id: 1, name: 'higk1',type:2}, {id: 2, name: 'higk2',type:2}, {id: 3, name: 'higk3',type:2} ] var ary3 = [] var ary4 = [] $.each(ary1,function(index,item){ var obj = {} for(var key in item){ obj['le'+key] = item[key] } ary3.push(obj) }) if(ary2.length==0){ $.each(ary1,function(index,item){ var obj = {} for(var key in item){ obj['ri'+key] = '' } ary4.push(obj) }) }else{ $.each(ary2,function(index,item){ var obj = {} for(var key in item){ obj['ri'+key] = item[key] } ary4.push(obj) }) } const mergedArray = [] $.each(ary3,function(index,item){ var obj = null $.each(ary4,function(ind,it){ if(index == ind){ obj = Object.assign(item,it) mergedArray.push(obj) return false } }) }) console.log(mergedArray);