换个思路修改数据结构中的键名

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

 

后端返回的数据结构:后端

  

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

组件所需的数据格式:数据结构

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

 

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

如下是解决思路: 转换为字符串,而且在replace操做时,只对字符串查找了一次。spa

 

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);
}
相关文章
相关标签/搜索