JS数组分类方法

匿名 (未验证) 提交于 2019-12-02 23:52:01
var spec = [{
    "id": 167,
    "goods_id": 24,
    "spec_id": 20,
    "spec_value_id": 55,
    "create_time": 1562495035,
    "spec_value_pid": "颜色",
    "spec_value": "红色"
   }, {
    "id": 168,
    "goods_id": 24,
    "spec_id": 20,
    "spec_value_id": 56,
    "create_time": 1562495035,
    "spec_value_pid": "颜色",
    "spec_value": "褐色"
   }, {
    "id": 169,
    "goods_id": 24,
    "spec_id": 25,
    "spec_value_id": 57,
    "create_time": 1562495035,
    "spec_value_pid": "重量",
    "spec_value": "400g"
   }, {
    "id": 170,
    "goods_id": 24,
    "spec_id": 25,
    "spec_value_id": 58,
    "create_time": 1562495035,
    "spec_value_pid": "重量",
    "spec_value": "500g"
   }];
  let obj = [];
  for (var i in spec) {
    if (!obj[spec[i].spec_value_pid]) {
    var arr = [];
    arr.push(spec[i]);
    obj[spec[i].spec_value_pid] = arr;
  } else {
    obj[spec[i].spec_value_pid].push(spec[i]);
  }
 }
  console.log(obj);

    let flag = 0,
      data = [];
    for(var i in spec) {
      var tt = '';
      for(var j in data) {
        if(data[j][0].spec_value_pid == spec[i].spec_value_pid) {
          flag = 1;
          tt = j;
          break;
        }
       }
      if(flag == 1) {
        data[tt].push(spec[i]);
        flag = 0;
      }else if(flag == 0) {
        let a = [];
        a.push(spec[i]);
        data.push(a);
      }
    }

    console.log(data);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!