js笔记:对象数组分类,遍历请求接口,深拷贝

1、数组遍历去请求接口 

 toOpen(data) {
      const _that = this
      const newD = [...data] // data是一个数组对象
      newD.forEach((item, index) => {
        // 获取工作站下面的设备
        wcGetStationApparatus({ wsid: item.wsid }).then((wcs) => {
          if (wcs.code === 0 || wcs.code === '0') {
            newD[index]['eqList'] = wcs.data
            _that.dataSources = JSON.parse(JSON.stringify(newD))
          }
          console.log('3')
        })
        // 获取工作中心下面的班组
        wcGetTeam({ wcid: item.wcid }).then((wcs) => {
          if (wcs.code === 0 || wcs.code === '0') {
            newD[index]['teamList'] = wcs.data
            _that.dataSources = JSON.parse(JSON.stringify(newD))
          }
          console.log('3')
        })
        //获取工作中心下的工位
        wcGetStation({ wcid: item.wcid }).then((res) => {
          if (res.code === 0 || res.code === '0') {
            newD[index]['stationList'] = res.data
            _that.dataSources = JSON.parse(JSON.stringify(newD))//必须在回调里面去赋值,只有接口请求成功了之后,才能去赋值
          }
          console.log('3')
        })
        console.log('2')
      })
      console.log('1')
    },

代码在浏览器运行

2/把若干数组按指定的字段名进行分组

function groupBy(list, propName) {
  return list.reduce((acc, item) => {
    const key = item[propName];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(item);
    return acc;
  }, {});
}

3/深度拷贝

function deepClone(obj) {
  if (obj === null) return null;
  if (typeof obj !== 'object') return obj;
  if (obj instanceof Date) {
    let date = new Date();
    date.setTime(obj.getTime());
    return date;
  }
  if (obj instanceof RegExp) {
    let re = new RegExp(obj.source);
    re.lastIndex = obj.lastIndex;
    return re;
  }
  let newObj = new obj.constructor();
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      newObj[key] = deepClone(obj[key]);
    }
  }
  return newObj;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值