From b1e5fa93eb28dea9f3a04536bfbe09ec210a9656 Mon Sep 17 00:00:00 2001 From: yazeedb Date: Tue, 10 Apr 2018 13:22:39 -0400 Subject: [PATCH] add snippet markdown file --- snippets/renameKeys.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 snippets/renameKeys.md diff --git a/snippets/renameKeys.md b/snippets/renameKeys.md new file mode 100644 index 000000000..c7f3386d0 --- /dev/null +++ b/snippets/renameKeys.md @@ -0,0 +1,22 @@ +### renameKeys + +Renames multiple object keys + +Get the object's keys with `Object.keys()` and return an object with the new keys, according to the `keysMap`, using `Array.reduce()`. + +The initial value is an empty object which is used as the accumulator, `acc`, in the callback function. Using the spread operator `(...)`, `acc` is continuously merged with a new object containing the new key and original object's value. If a new key doesn't exist, fallback to original object's key. + +```js +const renameKeys = (keysMap, obj) => Object + .keys(obj) + .reduce((acc, key) => ({ + ...acc, + ...{ [keysMap[key] || key]: obj[key] } + }), {}); +``` + +```js +const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 }; +renameKeys({ name: 'firstName', job: 'passion' }, obj); +// { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 } +```