【问题标题】:How to check if value exist when using lodash sortBy?使用 lodash sortBy 时如何检查值是否存在?
【发布时间】:2017-11-02 09:04:56
【问题描述】:

我正在使用 lodash 对数组进行排序,使用以下代码:

this.employees = _.orderBy(this.employees, [employee => employee.acf.user_department.name], [order]);

如果该值没有数据则失败,那么如何检查该值是否存在/处理未定义的值?

我正在尝试学习使用这些花哨的箭头函数,所以如果解释可以包含如何以 ES6 方式进行操作会很好。

【问题讨论】:

  • 你能放一个演示员工数组吗?

标签: arrays sorting lodash


【解决方案1】:

使用 lodash 的 _.get() - 它可以迭代路径(第二个参数),如果部分路径丢失,你会得到 undefined 或默认值(第三个参数)而不是错误:

_.get(employee, 'employee.acf.user_department.name', null)

示例:

const employee = {};

const result = _.get(employee, 'employee.acf.user_department.name', 'I\'m the default'); // the 3rd param is a default value

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

在你的排序方法中(默认为空字符串):

this.employees = _.orderBy(this.employees, [employee => _.get(employee, 'employee.acf.user_department.name', '')], [order]);

【讨论】:

    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多