js modifies the key value of the object array

//原数据
dataOld: [{
    
     count: '33', area: '122.2', districtId: 43000 }, {
    
     count: '44', area: '168.2', districtId: 43001 }] 
//接口需要的数据
dataNew: [{
    
     countAll: '33', countArea: '122.2', districtId: 43000 }, {
    
     count: '44', area: '168.2', districtId: 43001 }]

Method 1: Use the map loop to create a new object in the map loop, assign the key of the item to be changed to the new key value in the newly created object, and then push to a newly created array dataNew;

let dataNew = []
  dataOld.map(item => {
    
    
    let datas = {
    
    
      countAll: item.count,
      countArea: item.area,
      districtId: item.districtId
    }
    dataNew.push(datas)
  })
  console.log(dataNew)

Method 2: Use map loop + replace to replace, through the loop and then replace the subclass JSON.stringify to change the attribute key;

let dataNew = [];    //新数组
dataOld.map(item => {
    
    
    let _item = JSON.parse(JSON.stringify(item).replace('count', 'countAll').replace('area', 'countArea'));
    dataNew.push(_item)
});

Method 3: Use forEach loop + for loop to change the attribute key through Object.keys();

convertKey (arr, key) {
    
    
    let dataNew = []; //新数组
    this.dataOld.forEach((item, index) => {
    
    
        let obj = {
    
    }; //新数组里的新对象
        for (var i = 0; i < key.length; i++) {
    
    
            obj[key[i]] = item[Object.keys(item)[i]]; //key值替换  
        }
        dataNew.push(obj);
    })
    console.log(dataNew,'dataNew');
    return dataNew;
},
                                            // 改变后的key
let dataNew = this.convertKey(this.dataOld, ['countAll', 'countArea', 'districtId']);

Guess you like

Origin blog.csdn.net/qq_52099965/article/details/129723868