【问题标题】:Selectively Destructure an object, based on key name根据键名选择性地解构对象
【发布时间】:2023-04-08 18:22:02
【问题描述】:

假设我有这个对象:

const someProps = { darkMode: true, underlineMistakes: false, spellingView: (...), grammerView: (...) };

我不一定知道任何道具的名称,除了 1+ 以“视图”结尾。

我只想解构以“view”结尾的键,我想做类似的事情:

const propsEndingInView = Object.keys(someProps).filter(prop => !prop.endsWith('View');
const {
  ...nonViewProps, // darkMode, underlineMistakes
  propsEndingInView // {spellingView: (...), grammerView: (...)}
} = someProps; 

我需要以某种方式将这两种道具分开,最好是同时

我想不出该怎么做,或者即使有可能。

【问题讨论】:

  • 如果你不知道键的名称,为什么要将它们解构为你也不知道名称的变量?!说你会成功,然后呢?之后你会写什么来访问你刚刚创建的那些变量?
  • @deceze 我正在尝试构建一个通用的选项卡组件,并将选项卡的标签基于道具。我才明白你的意思,让我修正一下这个例子。
  • 您可以在不进行解构的情况下执行此操作,您是否有特殊原因不想“手动”处理它?
  • 当您拥有 propsEndingInView 时,您已经拥有了钥匙。发布您可以简单地获取 someProps[propsEndingInView[0]] 等值的帖子。但是我认为您可能想要映射那些

标签: javascript ecmascript-6 destructuring


【解决方案1】:

解构只是获取您已经知道的属性的方法。你不能通过解构来做到这一点。您可以创建自定义方法来过滤掉键以获取对象的子集

const someProps = {
  darkMode: true,
  underlineMistakes: false,
  spellingView: 'spellingView',
  grammerView: 'grammerView'
};

const subset = Object.fromEntries(
  Object.entries(someProps).filter(([k]) => k.endsWith('View'))
)

console.log(subset)

【讨论】:

    【解决方案2】:

    这不能通过解构来完成,但你可以编写一些代码来做到这一点。例如:

    const extract = (obj, regex) => 
      Object
        .entries(obj)
        .filter(([k]) => (typeof k === 'string') && regex.test(k))
        .reduce((out, [k, v]) => (
          out[k] = v,
          out
        ), {})
    
    const someProps = { darkMode: true, underlineMistakes: false, spellingView: '(...)', grammerView: '(...)' };
    
    const propsEndingInView = extract(someProps, /View$/)
    console.log(propsEndingInView)

    【讨论】:

      【解决方案3】:

      如果我理解正确,您希望得到一个仅包含来自someProps 的属性,其名称以View 结尾的对象。您可以执行以下操作:

      const viewProps = Object.keys(someProps).reduce((props, propName) => {
        // Here we check whether propName ends in View
        // If it does we add it to the object, if not we leave the object as it is
        return propName.match(/View$/) ? { ...props, [propName]: someProps[propName] } : props;
      }, {});
      

      这有帮助吗?你可以找到关于Array.reducehere的文档。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-28
        • 1970-01-01
        • 2016-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-24
        • 2014-08-04
        相关资源
        最近更新 更多