Update renameKeys.md

This commit is contained in:
Angelos Chalaris
2018-04-10 23:03:42 +03:00
committed by GitHub
parent f11d74db68
commit d40f859288

View File

@ -1,24 +1,19 @@
### renameKeys ### renameKeys
Renames multiple object keys Replaces the names of multiple object keys with the values provided.
Get the object's keys with `Object.keys()` and return an object with the new keys, according to the `keysMap`, using `Array.reduce()`. Use `Object.keys()` in combination with `Array.reduce()` and the spread operator (`...`) to get the object's keys and rename them according to `keysMap`.
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 ```js
const renameKeys = (keysMap, obj) => const renameKeys = (keysMap, obj) => Object
Object.keys(obj).reduce( .keys(obj)
(acc, key) => ({ .reduce((acc, key) => ({
...acc, ...acc,
...{ [keysMap[key] || key]: obj[key] } ...{ [keysMap[key] || key]: obj[key] }
}), }), {});
{}
);
``` ```
```js ```js
const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 }; const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
renameKeys({ name: 'firstName', job: 'passion' }, obj); renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
// { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
``` ```