如何在 Lodash 中将函数从数组链接到对象

How to chain functions from array to object in Lodash

我希望这项工作成功,但没有成功:

var myName = _(myArray)
    .find({ "ID": 5 })
    .get("Name");

基本上我想在数组中找到一个元素,其中 ID 属性 等于 5,然后获取 "Name" 属性 的值。

我错过了什么?

这里不需要使用.get().find() returns 匹配的对象,所以要拉它的 Name 属性 你可以简单地在那个对象上引用 .Name:

var myName = _(myArray).find({ "ID": 5 }).Name;

这仅在 .find() 调用成功时有效。您可能希望将 .find() 的结果存储在一个变量中,然后在返回 Name 属性:

之前检查它是否不是 null
var match = _(myArray).find({ "ID": 5 }),
    myName;

if (match) {
    myName = match.Name;
}

下面,我编写了三个不同的调用,它们都将 return 所需的数据。正如他们所说,在编程方面,剥猫皮的方法不止一种。您必须根据您的需要选择最有效或最高效的。

下面的后两个函数使用了 _.result 函数,改编自 lodash 文档。您可以使用结果替代 _.get().

_.result(object, path, [defaultValue])

This method is like _.get except that if the resolved value is a function it’s invoked with the this binding of its parent object and its result is returned.

Arguments

  • object (Object): The object to query.
  • path (Array|string): The path of the property to resolve.
  • [defaultValue] (*): The value returned if the resolved value is undefined.

Returns

  • (*): Returns the resolved value.

var myArray = [
  { ID : 0,  Name : 'Foo' },
  { ID : 1,  Name : 'Bar' },
  { ID : 5,  Name : 'Baz' },
  { ID : 10, Name : 'Oof' }
];

// Convienience function to print to the DOM. (Only for debugging)
function print() {
  document.body.innerHTML += '<p>' + [].join.call(arguments, ' ') + '</p>';
}

// Find item using chaining with `_.find()` and `_.get()`.
print(
  '<span class="lbl">Chain + Find + Get:</span>',
  _(myArray).chain().find({ 'ID' : 5 }).get('Name')
);

// Find item using a predicate (function).
print(
  '<span class="lbl">Find (Function Predicate) + Result:</span>',
  _.result(_.find(myArray, function(chr) {
    return chr.ID === 5;
  }), 'Name')
);

// Find item using the `_.matches()` callback shorthand.
print(
  '<span class="lbl">Find (Object Predicate) + Result:</span>',
  _.result(_.find(myArray, { 'ID' : 5 }), 'Name')
);
.lbl {
  font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>