How to change the keys in one object with javascript?

痞子三分冷 提交于 2019-12-25 08:57:23

问题


I have:

    var myAbc = { 0: true, 1: false, 2: true };

and i want to change de keys like:

var myAbc = { key1: true, key2: false, key3: true };

i have already tried this:

 for (var key in array) {
            key = value;
        }

but did not change the key of the array out side of the for, any help?


回答1:


If you can use es6, you can do this in one line:

var myAbc = { 0: true, 1: false, 2: true };

var renamed = Object.keys(myAbc).reduce((p, c) => { p[`key${Number(c)+1}`] = myAbc[c]; return p; }, {})

console.log(renamed)



回答2:


Something like this perhaps?

for(let key in myAbc){
    myAbc["key" + key] = myAbc[key];
    delete myAbc[key];
}

var myAbc = { 0: true, 1: false, 2: true };
console.log("Before", myAbc);

for(let key in myAbc){
    myAbc["key" + key] = myAbc[key];
    delete myAbc[key];
}
console.log("After", myAbc);



回答3:


Try this function:

function changeObjectKeys(sourceObject, prepondText){
    var updatedObj = {};
    for(var key in sourceObject){
        updatedObj[prepondText + key] = sourceObject[key];
    }
    return updatedObj;
}

Check here



来源:https://stackoverflow.com/questions/47214090/how-to-change-the-keys-in-one-object-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!