我如何通过 id 找到我的 lodash 对象?
How can I find my object with lodash by id?
我有一个包含以下内容的 userData 对象(来自 redux 存储):
"packs": [
{
"name": "Docos",
"id": "101",
"price": 1000,
"gifted": false
},
{
"name": "Entertainment Plus",
"id": "102",
"price": 1000,
"gifted": false
}]
我正在尝试找到第一个这样的:
let pack = _.find(this.props.userData.packs, 'id', "101")
但是当我 运行 它说包未定义?为什么?
阅读 lodash 文档并观看示例
_.find
Arguments
collection (Array|Object): The collection to inspect.
[predicate=_.identity] (Function): The function invoked per iteration.
[fromIndex=0] (number): The index to search from.
1 shorthand
_.find(this.props.userData.packs, {id: '101'})
2 shorthand
_.find(this.props.userData.packs, ['id', '101'])
根据 Lodash documentation,正确的语法应该是以下之一:
_.find(this.props.userData.packs, function(p) { return p.id === '101'; });
_.matches
iteratee shorthand.
_.find(this.props.userData.packs, { 'id': '101' });
_.matchesProperty
iteratee shorthand.
_.find(this.props.userData.packs, [ 'id': '101' ]);
从 lodash 文档中阅读更多内容:https://lodash.com/docs/4.16.6#find
我有一个包含以下内容的 userData 对象(来自 redux 存储):
"packs": [
{
"name": "Docos",
"id": "101",
"price": 1000,
"gifted": false
},
{
"name": "Entertainment Plus",
"id": "102",
"price": 1000,
"gifted": false
}]
我正在尝试找到第一个这样的:
let pack = _.find(this.props.userData.packs, 'id', "101")
但是当我 运行 它说包未定义?为什么?
阅读 lodash 文档并观看示例
_.find
Arguments
collection (Array|Object): The collection to inspect.
[predicate=_.identity] (Function): The function invoked per iteration.
[fromIndex=0] (number): The index to search from.
1 shorthand
_.find(this.props.userData.packs, {id: '101'})
2 shorthand
_.find(this.props.userData.packs, ['id', '101'])
根据 Lodash documentation,正确的语法应该是以下之一:
_.find(this.props.userData.packs, function(p) { return p.id === '101'; });
_.matches
iteratee shorthand.
_.find(this.props.userData.packs, { 'id': '101' });
_.matchesProperty
iteratee shorthand.
_.find(this.props.userData.packs, [ 'id': '101' ]);
从 lodash 文档中阅读更多内容:https://lodash.com/docs/4.16.6#find