是否有一种方法可以用Ramda覆盖对象中的道具名称?

时间:2018-08-21 02:24:57

标签: functional-programming ramda.js

我有这个对象{thing1: {}, thing2: {}},有一种方法可以覆盖诸如{thing1: {}, thing3not2: {}}这样的道具名称

2 个答案:

答案 0 :(得分:1)

不确定是否有更快/更简便的方法,但是可以结合使用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>

答案 1 :(得分:0)

Ramda“食谱”包含一个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": {}}