叶南淮
叶南淮
  • 发布:2020-01-02 14:27
  • 更新:2020-01-02 16:49
  • 阅读:1609

js数组怎么按属性分类,不用嵌套遍历

分类:HBuilderX

后台给了商品的数据接口,要按同一供应商分类渲染。其中 gysid是供应商的名字,现在已经按gysid排序好了。
数据格式:
[{spid:01,gysid:a,spname:商品1,price:2},
{spid:02,gysid:a,spname:商品2,price:21},
{spid:03,gysid:b,spname:商品3,price:56},
{spid:04,gysid:c,spname:商品4,price:21},
{spid:05,gysid:c,spname:商品5,price:23}]

要实现如下图效果,供应商的名字加这类商品,不能用嵌套遍历!!求大神帮忙!!!

2020-01-02 14:27 负责人:无 分享
已邀请:
菜鸡

菜鸡

把后端返回的数据遍历一遍
遍历成如下形式

[  
  {  
    gysid:a,  
    goodsList: [{spid:01,gysid:a,spname:商品1,price:2},{spid:02,gysid:a,spname:商品2,price:2}]  
  },  
  {  
    gysid:b,  
    goodsList: [{spid:01,gysid:b,spname:商品3,price:2}]  
  }  
]

进行页面渲染即可

IT梅

IT梅 - 一个前端开发者

let arr = [{spid:'01',gysid:"a",spname:"商品1",price:2},  
{spid:'02',gysid:"a",spname:"商品2",price:21},  
{spid:'03',gysid:"b",spname:"商品3",price:56},  
{spid:'04',gysid:"c",spname:"商品4",price:21},  
{spid:'05',gysid:"c",spname:"商品5",price:23}]  

let obj = arr.reduce((last,item)=>{  
     if(last[item.gysid]){  
         last[item.gysid].push(item)  
     }else{  
         last[item.gysid]=[item]  
     }  
    return last  
},{})  

console.log(obj);  

循环obj即可
  • 叶南淮 (作者)

    解决了 谢谢

    2020-01-03 09:28

该问题目前已经被锁定, 无法添加新回复