【发布时间】:2016-10-18 05:54:28
【问题描述】:
我正在尝试从我的学生数组中获取所有具有匹配 id 的对象,并从中获取其他属性值...
例如,我的数组如下所示:
const students = [
{id: 1, name: 'Cal', location: 'McHale' },
{id: 2, name: 'Courtney', location: 'Sydney Hall' },
{id: 1, name: 'Cal', location: 'Syndey hall' }
]
所以我的预期输出将获取 id: 1 的所有实例。
{id: 1, name: 'Cal', location: 'McHale' },
{id: 1, name: 'Cal', location: 'Syndey hall' }
我最终会想要删除重复的名称并显示在这样的列表中......(但这是下线。现在我只想抓取匹配的对象)。
Id: 1 Name: Cal Location: McHale
Syndey Hall
我试过了:
const result = _.find(students, {student_id: studentId});
但这似乎不起作用,它只是返回具有该 id 的对象之一..
{id: 1, name: 'Cal', location: 'McHale' },
我怎样才能做到这一点?
【问题讨论】:
-
lodash.com/docs#filter - 也就是说,鉴于您要过滤的是一个数组,而不是一个对象,在这种情况下您甚至不需要 Lodash。您可以使用内置的Array.prototype.filter() 函数。
-
@JoeClay 呵呵,lodash 过滤器似乎更容易。使用 . Array.prototype.filter()
students.filter(x => x.student_id === studentId);? -
@Modelesq 内置的可能更快,因为 lowdash 的功能更多:github.com/lodash/lodash/blob/4.13.1/lodash.js#L8458
-
@JustGage 字。感谢您的回复:D
-
是的,@JustGage 是对的——总的来说,如果可能的话,我更倾向于使用内置方法而不是 Lodash,因为它们倾向于用本机代码而不是 JavaScript 来实现,而 JavaScript 通常最终会更快。也就是说,除非这发生在代码中对性能非常关键的部分,否则它可能不会产生重大影响!
标签: javascript arrays lodash