+ 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
7 Réponses
+ 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'))
+ 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"
}
+ 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}
0
Josh Greig can you do this on the play Ground Because your approach same quite useful
0
Josh Greig oops it generate error when I pass it my argument
0
Josh Greig 🙏🙏🙏👍👍💯💯 thank you for help the it work Sir
0
Another alternative solution
https://code.sololearn.com/cA15a1a19847