0

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?

erik.hac
  • 111
  • 1
  • 9

3 Answers3

3

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);
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
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)
CRice
  • 29,968
  • 4
  • 57
  • 70
  • As noted by @Derek朕會功夫, this creates a new object with your desired keys (which is not the same as renaming existing keys). It can be reassigned back onto `myAbc`, but any existing references to `myAbc` will not be updated. If you want to mutate the object, Derek's answer will do that. That said, imo, you should avoid mutation anyway. – CRice Nov 10 '17 at 01:16
1

Try this function:

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

Check here

Wasim
  • 51
  • 7