Skip to content Skip to sidebar Skip to footer

How To Change The Keys In One Object With Javascript?

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

Solution 1:

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

Solution 2:

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)

Solution 3:

Try this function:

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

Check here

Post a Comment for "How To Change The Keys In One Object With Javascript?"