Last active
May 17, 2024 01:54
-
-
Save microbial/b99af0a7eb11cb680c14 to your computer and use it in GitHub Desktop.
lodash helpers - rename (renames object keys)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* var person = { firstName: 'bill', lastName: 'johnson' } | |
* | |
* person = _.rename(person, 'firstName', 'first') | |
* person = _.rename(person, 'lastName', 'last') | |
* | |
* console.log(person) // { first: 'bill', last: 'johnson' } | |
*/ | |
_.rename = function(obj, key, newKey) { | |
if(_.includes(_.keys(obj), key)) { | |
obj[newKey] = _.clone(obj[key], true); | |
delete obj[key]; | |
} | |
return obj; | |
}; | |
Please advise that .contains
needed to be changed for .includes
to work for me.
Thanks!
Immutable way of renaming a key in modern vanilla JS:
let obj = { oldKey: 1, b: 2, c: 3 }
const { oldKey: newKey, ...rest } = obj
obj = { newKey, ...rest }
obj // => { newKey: 1, b: 2, c: 3 }
I think this function should preserve the input parameter
export const rename = (obj, key, newKey) => {
const newObj = { ...obj };
if(_.includes(_.keys(newObj), key)) {
newObj[newKey] = _.clone(newObj[key], true);
delete newObj[key];
}
return newObj;
};
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, exactly what i was looking for !