有没有一种方法可以用 Ramda 覆盖对象中的道具名称?
Is there a method to override prop name in object with Ramda?
我有这个对象{thing1: {}, thing2: {}}
有没有一种方法可以只覆盖像 {thing1: {}, thing3not2: {}}
这样的道具名称
不确定是否有 quicker/easier 方法,但您可以结合使用 assoc
来添加新密钥和 dissoc
来删除旧密钥:
const { curry, assoc, dissoc } = R;
const renameProp = curry(
(oldName, newName, obj) =>
dissoc(oldName, assoc(newName, obj[oldName], obj))
);
const myTransformation = renameProp("thing2", "thing3not2");
const myResult = myTransformation( {thing1: {}, thing2: {} } );
console.log(JSON.stringify(myResult, null, 4));
<script src="https://cdn.jsdelivr.net/npm/ramda@0.25.0/dist/ramda.min.js"></script>
Ramda "cookbook" 包含一个 renameKeys
函数
https://github.com/ramda/ramda/wiki/Cookbook#rename-keys-of-an-object
下面是从那里复制的:
/**
* Creates a new object with the own properties of the provided object, but the
* keys renamed according to the keysMap object as `{oldKey: newKey}`.
* When some key is not found in the keysMap, then it's passed as-is.
*
* Keep in mind that in the case of keys conflict is behaviour undefined and
* the result may vary between various JS engines!
*
* @sig {a: b} -> {a: *} -> {b: *}
*/
const renameKeys = R.curry((keysMap, obj) =>
R.reduce((acc, key) => R.assoc(keysMap[key] || key, obj[key], acc), {}, R.keys(obj))
);
并调用它
renameKeys({thing2: 'thing3not2'}, {thing1: {}, thing2: {}})
=> {"thing1": {}, "thing3not2": {}}
我有这个对象{thing1: {}, thing2: {}}
有没有一种方法可以只覆盖像 {thing1: {}, thing3not2: {}}
不确定是否有 quicker/easier 方法,但您可以结合使用 assoc
来添加新密钥和 dissoc
来删除旧密钥:
const { curry, assoc, dissoc } = R;
const renameProp = curry(
(oldName, newName, obj) =>
dissoc(oldName, assoc(newName, obj[oldName], obj))
);
const myTransformation = renameProp("thing2", "thing3not2");
const myResult = myTransformation( {thing1: {}, thing2: {} } );
console.log(JSON.stringify(myResult, null, 4));
<script src="https://cdn.jsdelivr.net/npm/ramda@0.25.0/dist/ramda.min.js"></script>
Ramda "cookbook" 包含一个 renameKeys
函数
https://github.com/ramda/ramda/wiki/Cookbook#rename-keys-of-an-object
下面是从那里复制的:
/**
* Creates a new object with the own properties of the provided object, but the
* keys renamed according to the keysMap object as `{oldKey: newKey}`.
* When some key is not found in the keysMap, then it's passed as-is.
*
* Keep in mind that in the case of keys conflict is behaviour undefined and
* the result may vary between various JS engines!
*
* @sig {a: b} -> {a: *} -> {b: *}
*/
const renameKeys = R.curry((keysMap, obj) =>
R.reduce((acc, key) => R.assoc(keysMap[key] || key, obj[key], acc), {}, R.keys(obj))
);
并调用它
renameKeys({thing2: 'thing3not2'}, {thing1: {}, thing2: {}})
=> {"thing1": {}, "thing3not2": {}}