How to change the Key name of a object | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to change the Key name of a object

Example I have a object { name:"John" title:"book" Color :"black" } I want to loop through the object and change the name of the title key to start if it equal and return a new object like this { name:"John", start :"book", Color:"black" } Josh Greig Here is my code https://code.sololearn.com/cZXZ3VfCgc95/?ref=app

12th Apr 2021, 8:13 AM
George S Mulbah II
George S Mulbah II - avatar
7 Answers
+ 3
Sir George wrote, "Josh Greig can you do this on the play Ground Because your approach same quite useful" Response: This worked when I fixed your Sololearn code. const obj = { name: 'Luke Skywalker', title: 'Jedi Knight', age: 23 }; // Assigning to `value` does **not** change the property // value! You need to do `obj[key] = newValue` function renameKey(obj, fromKey, toKey) { result = Object.assign({}, obj); // clone so we don't modify the original. delete result[fromKey]; result[toKey] = obj[fromKey]; return result; } console.log(renameKey(obj,'title','start')) The fixes I made to your code were: - made k capital for parameters in: function renameKey(obj, fromKey, toKey) { - added quotes around title and start in this line: console.log(renameKey(obj,'title','start'))
12th Apr 2021, 9:03 AM
Josh Greig
Josh Greig - avatar
+ 1
Does this do what you want? Instead of looping through all the key-value pairs, you could use Object.assign to create a clone. Then, you just remove the old key and set the new one. function renameKey(obj, fromKey, toKey) { result = Object.assign({}, obj); // clone so we don't modify the original obj. delete result[fromKey]; result[toKey] = obj[fromKey]; return result; } renameKey({ name:"John", title:"book", Color :"black" }, 'title', 'start') will return { name:"John", start :"book", Color:"black" }
12th Apr 2021, 8:38 AM
Josh Greig
Josh Greig - avatar
+ 1
Josh Greig Here is the full code for replacing keys based on object that maps the values to replace: https://code.sololearn.com/cYBi89GsnmbO/?ref=app This will output an array with three objects where keys are replaced. If you want to create a new object out of them, just: const newTab = replacedItems.reduce((a, b) => Object.assign({}, a, b)); This outputs: {"a_b_c": 1, "d_e_f": 40, "xyz": 50}
12th Apr 2021, 8:39 AM
Matias
Matias - avatar
0
Josh Greig can you do this on the play Ground Because your approach same quite useful
12th Apr 2021, 8:49 AM
George S Mulbah II
George S Mulbah II - avatar
0
Josh Greig oops it generate error when I pass it my argument
12th Apr 2021, 9:05 AM
George S Mulbah II
George S Mulbah II - avatar
0
Josh Greig 🙏🙏🙏👍👍💯💯 thank you for help the it work Sir
12th Apr 2021, 9:22 AM
George S Mulbah II
George S Mulbah II - avatar
0
Another alternative solution https://code.sololearn.com/cA15a1a19847
13th Apr 2021, 6:16 AM
ODLNT
ODLNT - avatar