【问题标题】:Can you dynamically deconstruct an object for usage with currying?您可以动态解构对象以供使用柯里化吗?
【发布时间】:2018-06-15 18:21:16
【问题描述】:

我一直在使用函数式 javascript,并且对使用解构的 util 函数有了一个想法。

是否可以使用...rest 传递对象键的名称以便稍后过滤掉属性?

通读 ...rest 文档,我没有看到任何关于解构的提及。

如果不能,有什么办法可以解决这个问题?

const stripObject = attr => ({ ...attr }) => ({ ...attr });

const getUserProps = stripObject(['_id', 'firstName']);

console.log(getUserProps({ _id: 1, firstName: 'foo', lastName: 'bar' }));

/*
I understand right now whats happening is the []
passed is being ignored and its just returning a 
function that passing in all the props 
{
  _id: 1,
  firstName: 'foo'
}
*/

【问题讨论】:

    标签: javascript ecmascript-next


    【解决方案1】:

    如果你喜欢传播东西,你可以传播一个特别准备的代理:)

    const stripObject = attrs => obj => ({ ...new Proxy(obj, {
        ownKeys() {
          return attrs
        }
      })
    });
    
    const getUserProps = stripObject(['_id', 'firstName']);
    
    console.log(getUserProps({
      _id: 1,
      firstName: 'foo',
      lastName: 'bar'
    }));

    【讨论】:

    • 不错!太棒了,前几天我正在阅读有关代理的文章,这似乎是一个真正的游戏规则改变者!将不得不更多地阅读它们
    • @JoeWarner 请记住,这个答案是为了好玩 :) 不推荐用于生产代码。
    • 哦,是的,这是用于在测试代码的辅助项目中进行黑客攻击,但非常有趣。
    【解决方案2】:

    { ...attr } in 参数位置表示“获取传入对象的所有属性并将其分配给分配给attr的新对象”。 IE。您只是在创建传入对象的浅层克隆。

    即这两个功能除了克隆部分是等价的

    ({...foo}) => foo
    foo => foo
    

    所以不,你想要的是不可能的(这种方式)。 你不能动态声明参数。

    如果您想提取特定的道具,您可以根据您的要求调整这种方法(One-liner to take some properties from object in ES 6):

    const stripObject = attr => obj => pick(obj, ...attr);
    

    【讨论】:

    • 我的意思是,从技术上讲,您可以使用 Function 构造函数动态定义参数,例如var func = new Function(params.join(','), '...') 但你不应该那样做 ;)
    【解决方案3】:

    在了解了我最初不可能的解决方案后,我最终使用的是减少最初传递的键,然后从对象中获取道具。

    const stripObject = keys => obj => {
      return keys.reduce((p, c) => (
        { ...p, [c]: obj[c] }
      ), {});
    };
    const getUserProps = stripObject(['_id', 'firstName']);
    
    console.log(getUserProps({
      _id: 1,
      firstName: 'foo',
      lastName: 'bar'
    }));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 2016-11-26
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多