zoukankan      html  css  js  c++  java
  • 换个思路修改数据结构中的键名

    在最近的一次开发中,用到了一个iview级联组件,不得不吐槽一下,这个组件对于数据格式要求比较严格,但整个项目的技术栈又选择了这个库,无奈只能改变返回的数据结构键名。

    后端返回的数据结构:

      

    [
      {
        id: 1,
        name: "美容",
       childrenIndustryList: [ { id: 10, name: "护肤" } ]
    }
    ]

    组件所需的数据格式:

    [
      {
        value: 1,
        label: "美容",
       children: [
           {
              value: 10,
              label: "护肤"
           }   
        ]   
       }   
    ]

    可看出数据格式是 一样的 ,但是要的属性名不同,那该怎么处理呢?  循环?? 数据量大的数据,循环很慢,并且是嵌套循环,更慢。

    以下是解决思路: 转换为字符串,并且在replace操作时,只对字符串查找了一次。

    export const changeIndustry = (attach) => {
      if (attach.length === 0) return attach;
      const jsonString = JSON.stringify(attach);
      const mo = {
        id: 'value',
        name: 'label',
        childIndustryList: 'children'
      };
      const rs = jsonString.replace(/id|name|childIndustryList/g,function(me) {
        return mo[me];
      });
      return JSON.parse(rs);
    }
  • 相关阅读:
    se 键盘鼠标操作事件
    警告框操作方法(alert弹窗)
    se自带截图方法
    CSS Selector 高级用法
    吃奶酪
    互不侵犯
    hdu1102
    P4744 Iron man
    玉米田
    状压dp题单
  • 原文地址:https://www.cnblogs.com/yunnex-xw/p/10025489.html
Copyright © 2011-2022 走看看