Given the following array:
const school = [
{ Students: 4, Teachers: 15, Department: 'Mathematics' },
{ Students: 4, Teachers: 15, Department: 'English' },
{ Students: 4, Teachers: 15, Department: 'Science'}
]
I am interested in retrieving all values associated with a specific key:
const students = [
{ Students: 4 },
{ Students: 4 },
{ Students: 4 }
]
Instead of using a for in loop, is there a way to achieve this utilizing methods like map
, filter
, find
, or reduce
? I have been struggling to extract the key value.
Solution:
school.map(data => `Students: ${data.Students}`);
You can encapsulate this functionality within a function:
getByKey(arr, val) {
arr.map(data => `${val}: ${data[val]}`);
}
getKey(school, Department)