-1

Apologies for the confusing wording but i hope the explanation with code below is more clear, basically I have an array of objects such:

const employees = [{
  name: 'Dave',
  role: 'IT'
}, {
  name: 'Jenny',
  role: 'Sales'
}, {
  name: 'Joel',
  role: 'Finance'
}]

now i want to create a function which finds the role of a person by searching their name, like:

const getEmployeeRole = (employeeName, employees) => {}

so i would expect:

console.log(getEmployeeRole('Joel', employees))

to return 'Finance'.

I know i can use:

employees.map(employees => employees.role)

to get the roles for all 3 objects, but i want it to specifically churn it out for a single object only.

Any help much appreciated

Edward
  • 5,942
  • 4
  • 38
  • 55

1 Answers1

0

You can use the Array.filter() method:

const employees = [{
  name: 'Dave',
  role: 'IT'
}, {
  name: 'Jenny',
  role: 'Sales'
}, {
  name: 'Joel',
  role: 'Finance'
}];

var person = "Jenny";

// Just filter the array based on an employee's name
console.log(employees.filter(function(emp){
  return emp.name === person;
}));
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71