查找所有具有匹配ID javascript的对象 [英] Find all objects with matching Ids javascript
问题描述
我正在尝试从我的学生数组中获取所有具有匹配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?
推荐答案
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的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!