js-替換對象數組的鍵名


數組如下:

const array=[
    {
        name:'張三',
        id:'111'
    },
    {
        name:'李四',
        id:'222'
       }
]

 由於在使用某些框架組件時,組件有必須的某些字段名,因此就需要將該數組進行轉換,方法如下:

 /**
 * 替換字段
 */
    handleDealFilter(arr, key, replaceKey) {
      let newArr = [];
      arr.forEach((item, index) => {
        for (var i = 0; i < key.length; i++) {
          item[key] = item[replaceKey];
        }
        newArr.push(item);
      });
      return newArr;
    },

  使用方法為:

const newArr=handleDealFilter(array,'label','name');
// 得到的數組為
   [
        {
            label:'張三',
            id:'111'
        },
    
        {
            label:'李四',
            id:'222'
        }
    ]

  


免責聲明!

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



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