【问题标题】:Curly Braces Inside a _.find Lodash Statement in an AngularJS appAngularJS 应用程序中 _.find Lodash 语句中的花括号
【发布时间】:2017-07-06 20:04:57
【问题描述】:

在我的新工作中,我继承了一个 AngularJS 项目的巨大混乱。我最近一直在尝试解决具有以下 Lodash 语句的错误:

 var group = _.find(groupList, {id: id});

从https://lodash.com/docs/3.10.1#find 上的可用文档(这是我能找到的最接近版本 3.7.0 的文档),_.find 函数迭代一个集合并返回该语句对其“真实”的第一个对象。表达式中的第二项表示要执行的函数。

但是,我对 {id: id} 在这种情况下所做的事情感到困惑。这是 Angular 表达式吗?它到底在做什么?任何帮助将不胜感激。

【问题讨论】:

  • 搜索属性id与id变量相同的对象。
  • 表达式中的第一个id是属性还是变量?

标签: javascript angularjs lodash


【解决方案1】:

这意味着 - 在数组中搜索一个对象,该对象具有属性id,变量值为id。

var groupList = [{ id: 21, name: 'cats' }, { id: 17, name: 'dogs' }, { id: 701, name: 'rats' }];

var id = 17;

var group = _.find(groupList, {id: id});

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

【讨论】:

  • 那么第一个id是变量还是属性?
  • 不,它是一个对象,例如{ id: null },变量id是第二个{ id: id }。
【解决方案2】:

也许尝试阅读您发布的链接中的所有文档?具体看例子:

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

_.result(_.find(users, function(chr) {
  return chr.age < 40;
}), 'user');
// => 'barney'

// using the `_.matches` callback shorthand
_.result(_.find(users, { 'age': 1, 'active': true }), 'user');
// => 'pebbles'

// using the `_.matchesProperty` callback shorthand
_.result(_.find(users, 'active', false), 'user');
// => 'fred'

// using the `_.property` callback shorthand
_.result(_.find(users, 'active'), 'user');
// => 'barney'

我相信第二个例子

// 使用_.matches 回调简写

回答你的问题。

【讨论】:

    猜你喜欢
    • 2019-07-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 2017-05-11
    相关资源
    最近更新 更多