Home > Net >  How can I manipulate key name in Object with Javascript
How can I manipulate key name in Object with Javascript

Time:11-29

I want to do change the name of a key in an Object. But when I want to do this with an if condition, I get this (Assignment to function parameter 'key') error. 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.

CodePudding user response:

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. An alternative that doesn't modify the key variable would be

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

CodePudding user response:

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)
  • Related