小結兩種修改json中的key屬性名的方法


tree型數據分多層級菜單,只有在其中某一級使用了a這個變量名,在其他層級的數據結構中使用的是b這個變量名,需要將key值統一成a或者b

json數據:

let zf_jsonObj = [
  {
    name: '用戶權限管理',
    children: [
      {
        name: '二級菜單',
        auth_item: [
          {
            name: '三級菜單',
            auth_item: []
          }
        ]
      }
    ]
  },
  {
    name: '管理人員設置',
    children: [
      {
        name: '二級菜單',
        auth_item: [
          {
            name: '三級菜單',
            auth_item: []
          }
        ]
      }
    ]
  }
]

方法一:使用正則來修改Tree型json數據中的key屬性名:

/**
* params date <array> 需要修改的json格式的數組
* params newKey <string> 需要修改成的key值
* params oldKey <string> 需要被修改的key值
*/
function changeTreeDate(zf_jsonObj, newKey, oldKey) {
  let str = JSON.stringify(zf_jsonObj);
  let reg = new RegExp(oldKey, 'g');
  let newStr = str.replace(reg, newKey);
  return JSON.parse(newStr);
}
let newJsonObj = changeTreeDate(zf_jsonObj, 'children', 'auth_item');
console.log(newJsonObj); // 輸入結果見res1_1

方法二:使用遞歸,修改json格式中的key屬性名

/**
* params date <array> 需要修改的json格式的數組
* params newKey <string> 需要修改成的key值
* params oldKey <string> 需要被修改的key值
*/
function changeTreeDate(date, newKey, oldKey) {
    date.forEach(item => {
        if (item[newKey]&&item[newKey].length>0) changeTreeDate(item[newKey], newKey, oldKey);
        
        else if (item[oldKey]) {
            item[newKey] = item[oldKey];
            delete item[oldKey];
            if (item[newKey].length) changeTreeDate(item[newKey], newKey, oldKey);
        }
    })
}
changeTreeDate(zf_jsonObj, 'children', 'auth_item');
console.log(zf_jsonObj); // 輸出結果見res1_1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM