【问题标题】:How to select the properties of an object based on the values of the nested properties of the object using Lodash?如何使用 Lodash 根据对象的嵌套属性值选择对象的属性?
【发布时间】:2020-01-07 09:08:39
【问题描述】:

我想根据对象的嵌套属性的值来选择对象的属性。我正在使用 Lodash pick() 方法如下。

const object = {
  a: {x: true, y: true,}
  b: {x: true, y: false,},
  c: {x: true, y: true,},
};

_.pick(object, y,);

我希望看到以下结果:

{
  a: {x: true, y: true,}
  c: {x: true, y: true,}
}

但是,相反,我得到了这个错误。

由于第 6 行的语法错误而无法运行
意外令牌,预期,(6:2)

我做错了什么?

注意: 如果没有优雅的 Lodash 解决方案,我将采用优雅的纯 Javascript 解决方案。

【问题讨论】:

    标签: javascript ecmascript-6 lodash


    【解决方案1】:

    使用_.pickBy(),并将y属性设置为谓词:

    const object = {
      a: {x: true, y: true,},
      b: {x: true, y: false,},
      c: {x: true, y: true,},
    };
    
    const result = _.pickBy(object, 'y');
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

    如果没有 lodash,您可以使用 Object.entries() 将对象转换为 [key, value] 对的数组,通过 valuey 属性过滤,然后使用 Object.fromEntries() 转换回对象:

    const object = {
      a: {x: true, y: true,},
      b: {x: true, y: false,},
      c: {x: true, y: true,},
    };
    
    const result = Object.fromEntries(
      Object.entries(object)
        .filter(([, o]) => o.y)
    );
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

    【讨论】:

      【解决方案2】:

      您的语法错误实际上是由于您的 object 定义中缺少逗号。 pick 可能不是你想要的,比如:

      const object = {
        a: {x: true, y: true,},
        b: {x: true, y: false,},
        c: {x: true, y: true,},
      };
      
      _.filter(object, (e) => e.y);
      

      【讨论】:

        猜你喜欢
        • 2018-07-31
        • 2018-07-02
        • 1970-01-01
        • 1970-01-01
        • 2019-03-09
        • 2021-05-21
        • 2017-09-10
        • 2018-01-16
        • 2016-05-12
        相关资源
        最近更新 更多