Reputation: 91
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?
Upvotes: 0
Views: 51
Reputation: 31
var pupils = [
{ id: 0, name: 'will' },
{ id: 1, name: 'megan' }
];
function findPupil(property, value, find) {
var find_value = '';
for (var i = 0; i < pupils.length; i++) {
if (find_value == '') {
Object.keys(pupils[i]).forEach(function (key) {
if (key == property && pupils[i][key] == value) {
find_value = pupils[i][find];
}
});
} else {
break;
}
}
console.log(find_value);
return find_value;
}
var name = findPupil('id', 1, 'name');
Upvotes: 0
Reputation: 26732
Most of your code is correct except for the part of your if
statement. Please find working example -
var pupils = [{
id: 0,
name: 'will'
},
{
id: 1,
name: 'megan'
}
];
function findPupil(property, value, find) {
let result
pupils.forEach(function(pupil) {
if (pupil[property] === value) {
result = pupil[find];
}
});
return result
}
var name = findPupil('id', 1, 'name');
console.log(name)
Upvotes: 0
Reputation: 21672
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"));
Upvotes: 0
Reputation: 191986
Use Array.find()
to find an object with the property you know, or a default if an object is not found. Extract the find
property from the object:
const pupils = [{"id":0,"name":"will"},{"id":1,"name":"megan"}];
const findPupil = (property, value, find) =>
(pupils.find(o => o[property] === value) || {})[find];
const name = findPupil('id', 1, 'name');
console.log(name);
Upvotes: 2