查找具有匹配 ID javascript 的所有对象
Find all objects with matching Ids javascript
我正在尝试从我的学生数组中获取所有具有匹配 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});
但这似乎不起作用,它只是 returns 具有该 ID 的对象之一..
{id: 1, name: 'Cal', location: 'McHale' },
我怎样才能使这个工作?
我会研究 filter 函数。它内置于 JavaScript。
这是它如何工作的一个例子。您需要做的就是找到一种方法来制作一个函数,该函数将判断它是否具有正确的 ID。
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
如果您看到 _.find
的文档,它说明
Iterates over elements of collection, returning the first element predicate returns truthy for.
你应该使用 _.filter
方法来满足你的需求
Iterates over elements of collection, returning an array of all elements predicate returns truthy for.
类似于
const result = _.filter(students, {student_id: studentId});
const result = students.filter(e => e.id === 1);
我正在尝试从我的学生数组中获取所有具有匹配 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});
但这似乎不起作用,它只是 returns 具有该 ID 的对象之一..
{id: 1, name: 'Cal', location: 'McHale' },
我怎样才能使这个工作?
我会研究 filter 函数。它内置于 JavaScript。
这是它如何工作的一个例子。您需要做的就是找到一种方法来制作一个函数,该函数将判断它是否具有正确的 ID。
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
如果您看到 _.find
的文档,它说明
Iterates over elements of collection, returning the first element predicate returns truthy for.
你应该使用 _.filter
方法来满足你的需求
Iterates over elements of collection, returning an array of all elements predicate returns truthy for.
类似于
const result = _.filter(students, {student_id: studentId});
const result = students.filter(e => e.id === 1);