查找所有具有匹配ID javascript的对象

编程入门 行业动态 更新时间:2024-10-24 05:23:23
本文介绍了查找所有具有匹配ID 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?

推荐答案

我会研究过滤器函数.它内置在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的对象

本文发布于:2023-10-26 23:19:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531645.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   ID   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!