我正在尝试从我的学生数组中获取所有具有匹配ID的对象,并从中获取其他属性值...
I'm trying to get all objects with matching id's from my students array and get other property values from them...
例如,我的数组如下所示:
For instance my array looks like this:
const students = [ {id: 1, name: 'Cal', location: 'McHale' }, {id: 2, name: 'Courtney', location: 'Sydney Hall' }, {id: 1, name: 'Cal', location: 'Syndey hall' } ]所以我的预期输出将获取所有id实例:1.
So my expected output would grab all instances of id: 1.
{id: 1, name: 'Cal', location: 'McHale' }, {id: 1, name: 'Cal', location: 'Syndey hall' }我最终想要删除重复的名称,并显示在这样的列表中……(但这很重要.现在,我只想获取匹配的对象).
I'll eventually want to remove duplicate names and display in a list like so... (But that's down the line. For now I just want to grab matching objects).
Id: 1 Name: Cal Location: McHale Syndey Hall我尝试过:
const result = _.find(students, {student_id: studentId});但这似乎不起作用,它只是返回具有该ID的对象之一.
But that doesn't seem to work, it just returns one of the objects with that id..
{id: 1, name: 'Cal', location: 'McHale' },我该如何进行这项工作?
How can I make this work?
推荐答案我会研究过滤器函数.它内置在JavaScript中.
I would look into the filter function. It's build into JavaScript.
这是它如何工作的一个例子.您需要做的就是找到一种方法来创建一个函数,该函数将告诉它是否具有正确的ID.
Here's an example of how it works. All you need to do is find a way to make a function that will tell if it has the proper id.
function isBigEnough(value) { return value >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44]更多推荐
查找所有具有匹配ID javascript的对象
发布评论