How to change the keys in one object with javascri

2019-08-21 11:36发布

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?

3条回答
贼婆χ
2楼-- · 2019-08-21 11:48

Try this function:

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

Check here

查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-21 11:59

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);

查看更多
Melony?
4楼-- · 2019-08-21 12:03

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)

查看更多
登录 后发表回答