替换对象的key

Posted on 2020-08-06 09:15  猫头唔食鱼  阅读(662)  评论(0编辑  收藏  举报

把后台获取的key,替换成自己的key

    var arr = [
            { nameTest: 'zs', ageTest: 12 },
            { nameTest: 'ls', ageTest: 13 },
        ]

        // 把对象里的key  nameTest和ageTest分别替换成name和age
        var keyMap = {
            "nameTest": "name",
            "ageTest": "age",

        };

        for (var i = 0; i < arr.length; i++) {
            var obj = arr[i];
            for (var key in obj) {
                var newKey = keyMap[key];
                if (newKey) {
                    obj[newKey] = obj[key];
                    delete obj[key];
                }
            }
        }

        console.log(arr);// [{name:'zs',age:12},{name:'ls',age:13}]