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?

2

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

2 Comments

You're right -- this is better if you actually want to change the object rather than create a new one.
This is shorter and easier to follow, +1
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)

1 Comment

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.
1

Try this function:

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

Check here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.