[d24f17c] | 1 | import { curry, has } from 'ramda';
|
---|
| 2 |
|
---|
| 3 | import renameKeysWith from './renameKeysWith';
|
---|
| 4 |
|
---|
| 5 | const valueOrKey = (keysMap) => (key) => {
|
---|
| 6 | if (has(key, keysMap)) {
|
---|
| 7 | return keysMap[key];
|
---|
| 8 | }
|
---|
| 9 | return key;
|
---|
| 10 | };
|
---|
| 11 |
|
---|
| 12 | /**
|
---|
| 13 | * Creates a new object with the own properties of the provided object, but the
|
---|
| 14 | * keys renamed according to the keysMap object as `{oldKey: newKey}`.
|
---|
| 15 | * When some key is not found in the keysMap, then it's passed as-is.
|
---|
| 16 | *
|
---|
| 17 | * Keep in mind that in the case of keys conflict is behaviour undefined and
|
---|
| 18 | * the result may vary between various JS engines!
|
---|
| 19 | *
|
---|
| 20 | * @func renameKeys
|
---|
| 21 | * @memberOf RA
|
---|
| 22 | * @since {@link https://char0n.github.io/ramda-adjunct/1.5.0|v1.5.0}
|
---|
| 23 | * @category Object
|
---|
| 24 | * @sig {a: b} -> {a: *} -> {b: *}
|
---|
| 25 | * @param {!Object} keysMap
|
---|
| 26 | * @param {!Object} obj
|
---|
| 27 | * @return {!Object} New object with renamed keys
|
---|
| 28 | * @see {@link https://github.com/ramda/ramda/wiki/Cookbook#rename-keys-of-an-object|Ramda Cookbook}, {@link RA.renameKeysWith|renameKeysWith}
|
---|
| 29 | * @example
|
---|
| 30 | *
|
---|
| 31 | * const input = { firstName: 'Elisia', age: 22, type: 'human' };
|
---|
| 32 | *
|
---|
| 33 | * RA.renameKeys({ firstName: 'name', type: 'kind', foo: 'bar' })(input);
|
---|
| 34 | * //=> { name: 'Elisia', age: 22, kind: 'human' }
|
---|
| 35 | */
|
---|
| 36 | const renameKeys = curry((keysMap, obj) =>
|
---|
| 37 | renameKeysWith(valueOrKey(keysMap), obj)
|
---|
| 38 | );
|
---|
| 39 |
|
---|
| 40 | export default renameKeys;
|
---|