[英]How can I manipulate key name in Object with Javascript
I want to do change the name of a key in an Object
.我想更改
Object
中密钥的名称。 But when I want to do this with an if condition, I get this (Assignment to function parameter 'key')
error.但是当我想在 if 条件下执行此操作时,我得到了这个
(Assignment to function parameter 'key')
错误。 How can i manipulate a key name?我如何操纵键名?
My Code:我的代码:
const personData = [];
Object.keys(testItem).forEach((key) => {
item = testItem[key];
if (key === 'Name'){
key = 'Person Name';
}
personData.push({ name: key, data: Object.values(item) })
});
testItem data:测试项目数据:
testItem = {Name: {...}, Surname: {...}}
I want the Name
key to change to Person Name
without error.我希望
Name
键无误地更改为Person Name
。
The key
variable was taken in as input for the foreach function, and you shouldn't modify it - it is meant as a read only variable. key
变量被作为 foreach function 的输入,你不应该修改它——它是一个只读变量。 An alternative that doesn't modify the key
variable would be不修改
key
变量的替代方法是
const personData = [];
Object.keys(testItem).forEach((key) => {
let newKey = key;
item = testItem[key];
if (key === 'Name'){
newKey = 'Person Name';
}
personData.push({ name: newKey, data: Object.values(item) })
});
I didn't get what you wanted to do, simply assign keys value to new key and delete previous one for example:我没有得到你想要做的,只需将键值分配给新键并删除以前的键,例如:
const personData = {
Name: 'John',
lastname: 'Doe'
};
personData.PersonName = personData.Name
delete personData.Name;
console.log(personData.PersonName)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.