Search code examples
javascriptarraysforeachjavascript-objects

Find a property (which is stored as a string in a variable) in an array of objects


I have an array of objects which store the data of different 'pupils'.

var pupils = [
{
    id: 0,
    name: 'will'
},
{
    id: 1,
    name: 'megan'
}
];

I want to create a function called 'findPupil' which takes three parameters: the property you know, the value you know it to be and the property you want to find.

Say you know that the pupil you are looking for has an id of 1 but you don't know their name. In this case, you would call the function like this:

var name = findPupil('id', 1, 'name'); // should now store 'Megan' as a string

Here is the function I have written:

function findPupil(property, value, find) {
pupils.forEach(function(pupil) {
    if(pupils[pupil][`${property}`] === value) {
      return pupils[pupil][`${find}`];
    }
  });
}

Calling this function returns the following:

Error: Cannot read property 'id' of undefined

How do I make this function work?


Solution

  • You could use .find() for that.

    var pupils = [{id: 0, name: 'will'},{id: 1,name: 'megan'}];
    
    function getByPropertyAndValue(knownProp, knownValue, desiredProperty) {
      let pupil = pupils.find(p => p[knownProp] === knownValue); //Find pupil by property and value
      return pupil && pupil[desiredProperty]; //Return the value, or undefined if not found
    }
    
    console.log(getByPropertyAndValue("id", 1, "name"));