0

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.

  • Can you add the data of `testItem`? – flyingfox Nov 29 '22 at 12:13
  • 3
    Your `item` variable should be declared with `const` or `let`. There's nothing wrong with assigning a value to a function parameter. That's not an error as far as JavaScript is concerned, so if something is complaining it's your IDE or a build tool (a "linter" checking your syntax). – Pointy Nov 29 '22 at 12:16
  • Please see [How to avoid no-param-reassign when setting a property on a DOM object](/q/35637770/4642212). – Sebastian Simon Nov 29 '22 at 12:18

2 Answers2

0

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) })
});
OuterSoda
  • 175
  • 8
0

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)
Shubham Dange
  • 173
  • 13