我想使用for in函数来更改键。我知道我可以用map来做但是可以用for in来做吗?
const meinObject = {
name: "Dominic",
plz: 9548,
};
for (let key in meinObject) {
key + "1" + meinObject[key]
console.log(key);
}
const meinObject = {
name: "Dominic",
plz: 9548,
};
for (let key in meinObject) {
key + "1" + meinObject[key] // this does not make sense
var value = meinObject[key]; // get dominic, then plz etc.
console.log('original', key, value);
meinObject[key] = 'overwrite!!!';
var value = meinObject[key]; // get dominic, then plz etc.
console.log('altered', key, value);
}
console.log('object after modification', meinObject);
好的,那么您可以做的是将密钥的值分配给新密钥,然后删除旧密钥。这里不使用for in循环,它更简单。
obj['newKey'] = obj['oldKey'];
delete obj['oldKey'];
或者
meinObject['key'] = meinObject['newKey']
delete meinObject['key']