Find all objects with matching Ids javascript

隐身守侯 提交于 2019-11-28 06:23:18

问题


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' }
]

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

I've tried:

const result = _.find(students, {student_id: studentId});

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?


回答1:


I would look into the filter function. It's build into JavaScript.

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]



回答2:


If you see the documentation for _.find it states

Iterates over elements of collection, returning the first element predicate returns truthy for.


You should use the _.filter method for what you want

Iterates over elements of collection, returning an array of all elements predicate returns truthy for.

Something like

const result = _.filter(students, {student_id: studentId});


来源:https://stackoverflow.com/questions/37863855/find-all-objects-with-matching-ids-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!