问题
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