一.reduce的使用方法


reduce方法需要传递两个参数一个参数是回调函数,另外一个参数是初始值,回调函数接收四个值分别是,accumulator累计值,currentValue当前值,currentIndex当前索引值,array原始数组,回调函数的返回值作为下次累计的初始值,使用方法如下:

array.reduce((accumulator,currentValue,currentIndex,array)=>{
  return updatedAccumulator
},initialValue)

二.开发真实案例


如下原数据,将这个原数据使用reduce处理成新的数据,并且只能使用reduce,不能使用其他函数访问。

const data = [
  {
    "zscp1": {
      "zscpFlag": true,
      "zscpFs": "90"
    }
  },
  {
    "zscp2": {
      "zscpFlag": true,
      "zscpFs": "100"
    }
  },
  {
    "zscp3": {
      "zscpFlag": false,
      "zscpFs": ""
    }
  }
];

处理后的数据格式:

{
  "zscp1": {
    "zscpFlag": true,
      "zscpFs": "90"
  },
  "zscp2": {
    "zscpFlag": true,
      "zscpFs": "100"
  },
  "zscp3": {
    "zscpFlag": false,
      "zscpFs": ""
  }
}

处理代码:

this.csfsInfo = res.reduce((acc, cur) => {
  let key = Object.keys(cur)[0];
  let value = cur[key];
  return { ...acc, ...{ [key]: value } };
}, {});
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。