首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否有方法用Ramda覆盖object中的支柱名称?

是否有方法用Ramda覆盖object中的支柱名称?
EN

Stack Overflow用户
提问于 2018-08-21 02:24:56
回答 2查看 431关注 0票数 0

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-21 08:39:02

不确定是否有一种更快/更简单的方法,但是可以将assoc添加新键和dissoc组合以删除旧键:

代码语言:javascript
复制
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));
代码语言:javascript
复制
<script src="https://cdn.jsdelivr.net/npm/ramda@0.25.0/dist/ramda.min.js"></script>

票数 1
EN

Stack Overflow用户

发布于 2018-08-21 13:31:09

Ramda“食谱”包含一个renameKeys函数https://github.com/ramda/ramda/wiki/Cookbook#rename-keys-of-an-object

下面是从那里复制的:

代码语言:javascript
复制
/**
 * 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))
);

并称之为

代码语言:javascript
复制
renameKeys({thing2: 'thing3not2'}, {thing1: {}, thing2: {}})
=> {"thing1": {}, "thing3not2": {}}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51940748

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档