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

Return single parameter to variable from filtered array

I realize this is probably going to have what to most will be a painfully obvious answer. And if there is a better way to do what I need than filtering the array by all means I am open to hear it.

var employeeName = 'John McCully';
const employeeChart = [{Name : 'John McCully', Email : 'jmccully@domain.com', startDate : '04/20/2023'}, {Name : 'Thomas Young', Email : 'Tyoung@domain.com', startDate : '04/30/2023'}];
var startDates = employeeChart.filter( function(employeeChart){return (employeeChart.Name==employeeName)} );

console.log(startDates);

My Goal:
I want to dynamically filter based on a variable and return a parameter from that array. I.E. John McCully’s Start date. But I want to return only the start date to a variable

So what am I missing from this point? If I try to slice the filtered shadow copy it returns nothing. But I also can’t quite figure out how to bring the shadow copy into a new variable. Pretty new to this whole bit and I don’t need to do much with it beyond this particular instance… I think

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

>Solution :

In your example code startDates is actually the result of the filter() call, which is an array of objects containing the employees which match your filter logic.

To get the start date property from one of these you can access it via that array. See the example below. Also note that I changed some of the variable names to better match what they contain.

const employees = [{
  Name: 'John McCully',
  Email: 'jmccully@domain.com',
  startDate: '04/20/2023'
}, {
  Name: 'Thomas Young',
  Email: 'Tyoung@domain.com',
  startDate: '04/30/2023'
}];

let filteredEmployees = employees.filter(employee => employee.Name === 'John McCully');
let employeeJonStartDate = filteredEmployees[0].startDate;

console.log(employeeJonStartDate);

Note that the [0] in the logic above only accesses the first element of the resulting array. If you want to get the start date of all matching employees, then you would need to use either map(), or a loop.

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