亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

js如何修改對(duì)象數(shù)組的key值

 更新時(shí)間:2024年02月28日 09:21:23   作者:Lemon今天學(xué)習(xí)了嗎  
這篇文章主要介紹了js如何修改對(duì)象數(shù)組的key值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

js修改對(duì)象數(shù)組的key值

實(shí)例

將dataOld這個(gè)對(duì)象數(shù)組的對(duì)象中的屬性key變成dataNew中的形式;

//原數(shù)據(jù)
dataOld: [{ count: '33', area: '122.2', districtId: 43000 }, { count: '44', area: '168.2', districtId: 43001 }] 
//接口需要的數(shù)據(jù)
dataNew: [{ countAll: '33', countArea: '122.2', districtId: 43000 }, { count: '44', area: '168.2', districtId: 43001 }]

方法一

使用map循環(huán),在map循環(huán)內(nèi)創(chuàng)建一個(gè)新對(duì)象,將item要改變的key賦給新創(chuàng)建的對(duì)象里面新key值,然后push給一個(gè)新創(chuàng)建的數(shù)組dataNew即可;

let dataNew = [];    //新數(shù)組
dataOld.map(item => {
    let obj = {
        countAll: item.count,
        countArea: item.area,
        districtId: item.districtId,
    }
     dataNew.push(obj);
});

方法二

使用map循環(huán) + replace替換,通過(guò)循環(huán)然后將子類JSON.stringify后采用replace來(lái)改變屬性key;

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

方法三

使用forEach循環(huán) + for循環(huán),通過(guò)Object.keys()來(lái)改變屬性key;

convertKey (arr, key) {
    let dataNew = []; //新數(shù)組
    this.dataOld.forEach((item, index) => {
        let obj = {}; //新數(shù)組里的新對(duì)象
        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']);

結(jié)果:

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論