Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run LINQ function in Java script to return an object from an Array

I have a javascript Array of object like this:

var PriorityList =[]
PriorityList.push({ Id: 4, Title: 'Very High' });
PriorityList.push({ Id: 3, Title: 'High' });
PriorityList.push({ Id: 2, Title: 'Normal' });
PriorityList.push({ Id: 1, Title: 'low' });
PriorityList.push({ Id: 1, Title: 'Very low' });

I want to choose find one of them by Id and return it’s Title
In c# I can run this code:

var selPer = PriorityList.Find(2).Title;

Or

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var selPer = PriorityList.First(p=>p.Id==2).Title;

but In JS , I don’t know how to use it?

>Solution :

JavaScript also has a Array#find which is very similar to the LINQ .First() method. It returns the first element that matches the given filter criteria. The only real difference to .First() is that Array#find does not throw an Exception when no matching element was found but instead returns undefined.

var PriorityList = [];
PriorityList.push({Id: 4, Title: "Very High"});
PriorityList.push({Id: 3, Title: "High"});
PriorityList.push({Id: 2, Title: "Normal"});
PriorityList.push({Id: 1, Title: "low"});
PriorityList.push({Id: 1, Title: "Very low"});

PriorityList.find(item => item.Id === 2).Title; // "Normal"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading