资讯专栏INFORMATION COLUMN

复杂数据处理

libin19890520 / 1026人阅读

摘要:前端对于数据的处理一般会用到等方法,下面逐次进行分析方法用于调用数组的每个元素,并将元素传递给回调函数。注意对于空数组是不会执行回调函数的。方法按照原始数组元素顺序依次处理元素。

前端对于数据的处理一般会用到foreach、map、reduce、Object.values()、Object.keys()、Object.entries()等方法,下面逐次进行分析

foreach
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。foreach方法不会返回执行结果。

注意: forEach() 对于空数组是不会执行回调函数的。foreach会改变原数组。

语法:
array.forEach(function(currentValue, index, arr), thisValue)
示例:
    let schedulesObj = {};
    dateArr.forEach((key) => {
      if (!schedulesObj[key]) {
        schedulesObj[key] = [];
      }
      schedulesObj[key].push(item);
    });

map
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

map() 方法按照原始数组元素顺序依次处理元素。

注意: map() 不会对空数组进行检测。

注意: map() 不会改变原始数组。

语法:
array.map(function(currentValue,index,arr), thisValue)
示例:
    const initItems = initEvaluateItems.map(item => {
      const { score, id, itemName, levelDesc, maxLevel } = item;
      return {
        score,
        id,
        itemName,
        levelDesc,
        maxLevel
      };
    });

reduce
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

reduce() 可以作为一个高阶函数,用于函数的 compose。

注意: reduce() 对于空数组是不会执行回调函数的。

语法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
示例:
let scheduleIdArray = Object.keys(curScheduleMonth).map(v => curScheduleMonth[v]).reduce((total, item) => {
    total = [...total, ...item];
    return total;
  }, []);

Object.keys()

Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用 for...in 循环遍历该对象时返回的顺序一致 。

语法:
Object.keys(obj)
示例:
var anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.keys(anObj)); // console: ["2", "7", "100"]

Object.values()

Object.values()方法返回一个给定对象自身的所有可枚举属性值的数组,值的顺序与使用for...in循环的顺序相同 ( 区别在于 for-in 循环枚举原型链中的属性 )。

语法:
Object.values(obj)
示例:
var an_obj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.values(an_obj)); // ["b", "c", "a"]

Object.entries()

Object.entries()方法返回一个给定对象自身可枚举属性的键值对数组,其排列与使用 for...in 循环遍历该对象时返回的顺序一致(区别在于 for-in 循环也枚举原型链中的属性)。

语法:
Object.entries(obj)
示例:
const anObj = { 100: "a", 2: "b", 7: "c" };
console.log(Object.entries(anObj)); // [ ["2", "b"], ["7", "c"], ["100", "a"] ]

1.时间相关

{
    "success":true,
    "code": "success",
    "message": "成功",
    "data": {
        "monthData":[
            {
               "month":"2018-05",
               "displayDesc":"有服务",
               "showType":"1",
               "tips":"请您选择"
            }
        ]
        "calendarData":[
            {
               "date":["2018-06-02","2018-07-09"],
               "displayDesc":"有服务",
               "showType":"1",
               "tips":"请您评价"
            }
        ],
        "schedules":[
            {
               "scheduleId":"1",
               "appCode":"106",
               "appName":"公共服务",
               "cityId":"321568",
               "categoryCode":"16",
               "scheduleType":"1",
               "userDesc":"社区医疗",
               "systemDesc":"",
               "remind":"1",
               "repeat":"1",
               "status":"2",
               "serviceUrl":"",
               "beginTime":"2018-04-25",
               "endTime":"2018-04-26",
            }
        ]
    }
}
import moment from "moment/moment";

/**
 * 通过beginTime和endTime,将列表值按照天的维度进行整理,产出的数据结构scheduleByDay
 * @param schedules
 */
export function genSchedulesObj(schedules = []) {
  let schedulesObj = {};
  schedules.forEach((item) => {
    let { beginTime, endTime } = item;
    let _beginTime = new Date(beginTime).getTime();
    let _endTime = new Date(endTime).getTime();
    let dateArr = [];
    let dateReduce = ((_endTime - _beginTime) / (1000 * 24 * 60 * 60) + 1) || 1;
    dateReduce > 0 ? {} : (dateReduce = 0);
    for (let i = 0; i < dateReduce; i++) {
      dateArr.push(moment(_beginTime).format("YYYY-MM-DD"));
      _beginTime += (1000 * 24 * 3600);
    }
    dateArr.forEach((key) => {
      if (!schedulesObj[key]) {
        schedulesObj[key] = [];
      }
      schedulesObj[key].push(item);
    });
  });
  // let flag = true;
  // for (let key in schedulesObj) {
  //   for (let i = 0, len = schedulesObj[key].length; i < len; i++) {
  //     if (schedulesObj[key][i].status < 3) {
  //       flag = false;
  //       break;
  //     }
  //   }
  // }
  return {
    schedulesObj
  };
}

/**
 * calendarData 日期上显示代办内容,根据这个数据创建tagData是一个一维数组,产出的数据结构tagDataByMonth
 * @param calendarData
 */
export function genCalendarDataObj(calendarData = []) {
  let calendarDataObj = {};
  calendarData.forEach((item) => {
    item.date.forEach((key) => {
      if (!calendarDataObj[key]) {
        calendarDataObj[key] = [];
      }
      calendarDataObj[key].push({
        displayDesc: item.displayDesc,
        showType: item.showType
      });
    });
  });
  return calendarDataObj;
}
/**
 * 获取当前月、上一个月、下一月及当前月的开始、结束日期
 */
export function getFormatMonth(currentDate) {
  const beginDate = moment(currentDate).startOf("month").add(-1, "M").format("YYYY-MM-DD");
  const endDate = moment(currentDate).endOf("month").add(1, "M").format("YYYY-MM-DD");
  const preMont = moment(currentDate).subtract(1, "months").format("YYYY-MM");
  const nextMont = moment(currentDate).add(1, "months").format("YYYY-MM");

  const currMont = moment(currentDate).format("YYYY-MM");

  const month = preMont + "," + currMont + "," + nextMont;

  return {
    beginDate,
    endDate,
    preMont,
    nextMont,
    currMont,
    month
  };
}

2.工具类函数

/**
 * 正则表达式获取地址栏参数
 */

export const getURLParameters = (url) => {
  url = url.split("?")[1] || "";
  url = url.split("&");
  return url.reduce((total, item) => {
    let itemArr = item.split("=");
    total[itemArr[0]] = itemArr[1];
    return total;
  }, {});
};

/**
 * filter过滤
 */
const filterArr = (scheduleByDay[currentDate] || []).filter(v => {
    return v.status !== 4;
  });


const tagData = Object.keys(tagDataByMonth).map((key) => {
    const obj = tagDataByMonth[key][0];
    const scheduleByDayItem = scheduleByDay[key] || [];
    return {
      date: key,
      tag: scheduleByDayItem.length === 1 ? scheduleByDayItem[0].userDesc : obj.displayDesc,
      tagColor: obj.showType === "1" ? "#F5A623" : "#CCCCCC"
    };
  });

let scheduleIdArray = Object.keys(curScheduleMonth).map(v => curScheduleMonth[v]).reduce((total, item) => {
    total = [...total, ...item];
    return total;
  }, []);
  let scheduleId = scheduleIdArray.length ? scheduleIdArray[0].scheduleId : null;
  let isOnlyOne = scheduleId ? scheduleIdArray.every(v => v.scheduleId === scheduleId) : false;

/**
   * 获取服务端时间
   */
  getServerTimeAsync() {
    return new Promise((resolve) => {
      try {
        my.call("getServerTime", (res) => {
          resolve(res.time);
        });
      } catch (e) {
        resolve(new Date().getTime());
      }
    });
  },
/**
   * 检查文本域的长度
   * @param keyword
   * @returns {*}
   */
  checkKeywordLength(keyword) {
    const { maxlength } = this.data;
    if (keyword.length > maxlength) {
      keyword = keyword.substring(0, maxlength);
    }
    return keyword;
  },


const { data: { items: initEvaluateItems } } = serviceKey;
    const initItems = initEvaluateItems.map(item => {
      const { score, id, itemName, levelDesc, maxLevel } = item;
      return {
        score,
        id,
        itemName,
        levelDesc,
        maxLevel
      };
    });

3.层级较深的数据结构

{
    "success": true, 
    "value": {
        "merchant": {
            "id": 0, #物理id
            "partakerId": 0, 
            "partakerName": "string", 
            "merchantPid": "string",
            "merchantName": "string", 
            "owners": {
                "guarantee_owner":[{"account":"string","name":"string"}],
            }, #负责人      
        },
        "extension":{
            keyValues: {
                channel:{
                    key:{
                        id:"21",
                        creator:"流年",
                        dataSource:"",
                        key:"duration",
                        label:"项目周期",
                        type:"date",
                        isRequire:"Y"   
                    },
                    value:"2018-06-02 17:55:12"
                },
                is_sign:{
                    key:{
                        id:"32",
                        creator:"lily",
                        dataSource:"[{"key":"current","value":"今天"},{"key":"last","value":"昨天"}]",
                        key:"startTime",
                        label:"启动时间",
                        type:"select",
                        isRequire:"N"   
                    },
                    value:"last"
                },
                merchantInfo:{
                    key:{
                        id:"02",
                        creator:"jack",
                        dataSource:"",
                        key:"taskCount",
                        label:"任务量",
                        type:"number",
                        isRequire:"Y"   
                    },
                    value:"55"
                },
                code:"DEFAULT",
                tempName:"社区服务"
            }
        }, #动态字段
        
    }, 
    "msg": "string", #错误信息
    "code": "string" #错误码
}




const { stat, value = {}, msg } = response || {};
      if (stat === "fail") {
        message.error(msg);
      }
      const { merchant = {}, extension = {} } = value;
      const { keyValues = {} } = extension;
      const extenData = Object.entries(keyValues).map(v => {
        const [arr1, arr2] = v;
        const { key, recordId, value: newValue } = arr2;
        return {
          key,
          value: newValue,
          recordId
        };
      });
      console.log("动态数据-----", extenData);


const linksObj = {
  活动信息: links.slice(0, 2),
  活动商户信息: links.slice(2, 8),
  保障商户信息: links.slice(8),
};     
   
   
   getFormDataDom = (data) => {
        const { getFieldDecorator } = this.props.form;
        const { formItem = {} } = this.props;
        return data.map((val) => {
          const { name, id, isSelect = false, isSelectInputOwners = false, isInput = false } = val;
          let isSimpleInitial;
          let isSelectInputOwnersInitial;
          if (isSelect || isInput) {
            isSimpleInitial = formItem && formItem[id] ? formItem[id] : "";
          }
          if (isSelectInputOwners) {
            isSelectInputOwnersInitial = formItem && formItem[id] && formItem[id].length > 0 ? formItem[id].map(v => v.name) : [];
          }
          const initialValue = isSelectInputOwners ? isSelectInputOwnersInitial : isSelect || isInput ? isSimpleInitial : "";
          return (
            
              
                {getFieldDecorator(`${id}`, {
                  initialValue
                })(this.getFormItem(formItem, val))
                }
              
            
          );
        });
  };
 
 
    
 extenArr = (extenData = []) => {
    return extenData.map((item) => {
      const { key, value } = item;
      const { fieldKey, fieldLabel } = key;
      let { dataSource } = key;
      let spanValue = "";
      if (dataSource === "") {
        spanValue = value;
      } else {
        try {
          dataSource = dataSource.replace(/"/img, """);
          const jsonValue = JSON.parse(dataSource);
          spanValue = jsonValue.reduce((total, i) => {
            total[i.key] = i.value;
            return total;
          }, {})[value];
        } catch (e) {
          spanValue = "";
        }
      }
      return {
        name: fieldLabel,
        id: fieldKey,
        spanValue
      };
    });
  };




        
{ Object.entries(linksObj) .map((item, index) => { const [item1, item2] = item; return

{item1}

{ this.getFormDataDom(item2) }
; }) } { this.getFormDataDom(this.extenArr(extenData)) }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/97503.html

相关文章

  • 数据结构大总结(链表篇)

    摘要:实际中更多是作为其他数据结构的子结构,如哈希桶图的邻接表等等。实际中使用的链表数据结构,都是带头双向循环链表。 文章目录 一.算法的时间复杂度和空间复杂度1.算法...

    不知名网友 评论0 收藏0
  • 十分钟弄懂:数据结构与算法之美 - 时间和空间复杂

    摘要:什么是复杂度分析数据结构和算法解决是如何让计算机更快时间更省空间的解决问题。分别用时间复杂度和空间复杂度两个概念来描述性能问题,二者统称为复杂度。复杂度描述的是算法执行时间或占用空间与数据规模的增长关系。这就是大时间复杂度表示法。 showImg(https://segmentfault.com/img/bVbtpFP?w=1000&h=574); 复杂度分析是整个算法学习的精髓,只要...

    Salamander 评论0 收藏0
  • 卷积神经网络的复杂度分析

    摘要:同样以里的模块为例,替换前后的卷积分支复杂度如下中使用与卷积级联替代卷积中提出了卷积的,在确保感受野不变的前提下进一步简化。 在梳理CNN经典模型的过程中,我理解到其实经典模型演进中的很多创新点都与改善模型计算复杂度紧密相关,因此今天就让我们对卷积神经网络的复杂度分析简单总结一下下。1.时间复杂度1.2 卷积神经网络整体的时间复杂度示例:用 Numpy 手动简单实现二维卷积假设 Stride...

    tracy 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<