0

I have obejct data like this :

{radiant: 11, dire: 22}

and I want to change it like this :

{aplha: 11, omega: 22}

how to do that?

  • 1. add a new property with different name 2. delete the old property. – VLAZ Oct 09 '20 at 09:26
  • I would create a function for that: ``` const obj = {radiant: 11, dire: 22}; const renameKey = (object, key, newKey) => { const clonedObj = object; const targetKey = clonedObj[key]; delete clonedObj[key]; clonedObj[newKey] = targetKey; return clonedObj; }; renameKey(obj, 'radiant', 'alpha'); renameKey(obj, 'dire', 'omega'); console.log(obj) ``` – Olivier Girardot Oct 09 '20 at 09:36
  • @OlivierGirardot I wouldn't use that function. It's not much of an improvement over doing it in two lines. Also, it's creating `clonedObj` which is in no way shape or form a cloned object but literally *the same* reference as the one passed in, so calling the function will always mutate the input. – VLAZ Oct 09 '20 at 09:38
  • True. The function is only useful if he wants to perform that operation agin in the futur for other objects, I guess. Yes you are right it is not a cloned object, I should have named it differently. Thanks! – Olivier Girardot Oct 09 '20 at 09:43

0 Answers0