CV工程师
2022-07-19 08:17:40 阅读:895
有时,我们想使用 Lodash 从 JavaScript 数组中查找并返回一个对象。
在本文中,我们将了解如何使用 Lodash 从 JavaScript 数组中查找并返回对象。
我们可以使用Lodash的find
方法找到一个带有谓词函数的对象,该函数返回我们正在寻找的对象的条件。
例如,我们可以写:
const arr = [{
description: 'object1',
id: 1
},
{
description: 'object2',
id: 2
},
{
description: 'object3',
id: 3
},
{
description: 'object4',
id: 4
}
]
const obj = _.find(arr, (o) => {
return o.description === 'object3';
});
console.log(obj)
我们传入数组作为第一个参数进行搜索。
我们传入谓词函数,该函数返回我们正在寻找的对象的条件作为第二个参数。
因此,obj
是:
{description: "object3", id: 3}
我们还可以传入一个对象作为第二个参数来搜索具有给定值的属性的对象:
const arr = [{
description: 'object1',
id: 1
},
{
description: 'object2',
id: 2
},
{
description: 'object3',
id: 3
},
{
description: 'object4',
id: 4
}
]
const obj = _.find(arr, {
description: 'object3'
});
console.log(obj)
我们可以传入一个带有属性键和值的数组来执行相同的搜索:
const arr = [{
description: 'object1',
id: 1
},
{
description: 'object2',
id: 2
},
{
description: 'object3',
id: 3
},
{
description: 'object4',
id: 4
}
]
const obj = _.find(arr, ['description', 'object3']);
console.log(obj)
它们都得到与第一个示例相同的结果。
我们可以使用 Lodash的find
方法在数组中查找具有给定条件的对象。
评论
扫描二维码获取文章详情
更多精彩内容尽在:WWW.ZNGG.NET