0

I have this :

  for (const key of Object.keys(filter)) {

}

Problem is that sometimes i get key with suffix _1, and than i have:

keyName_1{
  prop:'prop1'
}

And when i call service this keyName_1 is a problem, so what i want is always to replace this keyName1. I tried this :

for (const key of Object.keys(filter)) {
      if(key.includes('_1')){

        key.replace('_1','');
      }
  }

But then i lose object values of that key, so my prop does not exists anymore. Is there any option to change only key name?.

None
  • 8,817
  • 26
  • 96
  • 171
  • This might be the answer to your question: https://stackoverflow.com/questions/4647817/javascript-object-rename-key – CodeSamurai Apr 13 '21 at 17:23
  • `key.replace('_1','');` is not going to alter the key in the object. That is just changing the string and you do nothing with it. – epascarello Apr 13 '21 at 17:28

2 Answers2

5

You can assign the value to a new key and delete the old one.

let o = {
  keyName_1: {
    prop: 'prop1'
  }
};
for (const key of Object.keys(o)) {
  if (key.includes('_1')) {
    o[key.replace('_1','')] = o[key];
    delete o[key];
  }
}
console.log(o);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

If you want to mutate your source object you can do it with this syntax.

delete Object.assign(o, {[nextKey]: o[prevKey] })[prevKey];

In case if you want to create new object, you can use below syntax.

const newObject = {};
delete Object.assign(newObject, o, {[nextKey]: o[prevKey] })[prevKey];