js修改对象的key值

举例说明

  • 原对象
sourceObj = {

    "name":'zhangsan',

    "age":''16'

}
  • 需要转换为
targetObj = {

    "label":'zhangsan',

    "value":''16'

}

实现代码:

let keymap = {
  name: "label",
  age: 'value'
}
Object.keys(sourceObj).map(keys => {
  let newKey = keymap[keys]
  if (newKey) {
    sourceObj[newKey] = sourceObj[keys]
    delete sourceObj[keys]
  }
})
  • 实际使用:
// 树形结构的转换
IndustryData(arr) {
  arr.forEach(v => {
    let keymap = {
      categoryId: "id",
      children: 'children',
      name: "label",
      order: 'order',
      parentId: "parentId",
    }
  
    Object.keys(v).map(keys => {
      let newKey = keymap[keys]
      if (newKey) {
        v[newKey] = v[keys]
      }
    })
    if (v.children && v.children.length > 0) {
      this.IndustryData(v.children)
    } else {
      delete v['children']
    }
  })
  return arr
}

 

你可能感兴趣的:(js)