If I were to create a function, were a persons name was entered, how would I return an array with the names of the pets from the object below, what would be the best method if I were to use a for loop to iterate over it? I've not quite learnt some of the ES6 features yet and i'm new to coding.
A typical array of owners is shown below:
[ { name: 'Malcolm', pets: ['Bear', 'Minu'], }, { name: 'Caroline', pets: ['Basil', 'Hamish'], }, ];
Thanks for the fast replies! :)
It's pretty simple to achieve it: you search for the corresponding owner with the find function, then, if you have an owner, you return the pets key, which is already an array according to the code provided. If you have no owner corresponding to the name entered, then you'll get "undefined", but you can customise this code to have an empty array if it better fits your needs.
const data = [{
name: 'Malcolm',
pets: ['Bear', 'Minu'],
}, {
name: 'Caroline',
pets: ['Basil', 'Hamish'],
}, ];
const getPetsByOwnerName = (ownerName) => {
const owner = data.find(d => d.name === ownerName);
return owner ? owner.pets : undefined;
}
const carolinePets = getPetsByOwnerName('Caroline');
console.log(carolinePets);
EDIT: author request to do it with a loop
const data = [{
name: 'Malcolm',
pets: ['Bear', 'Minu'],
}, {
name: 'Caroline',
pets: ['Basil', 'Hamish'],
}, ];
function getPetsByOwnerNameWithLoop(ownerName) {
for (let i = 0; i < data.length; i++) {
if (data[i].name === ownerName) {
return data[i].pets;
}
}
return undefined;
}
const carolinePets = getPetsByOwnerNameWithLoop('Caroline');
console.log(carolinePets);
Try filter() method. The function returns an array of names from the filtered owner as a result.
Example code:
const arr = [
{ name: 'Malcolm', pets: ['Bear', 'Minu'], },
{ name: 'Caroline', pets: ['Basil', 'Hamish'], }
];
function petsNames(val) {
return arr.filter(x => x.name === val)[0].pets;
};
console.log(petsNames('Malcolm'));
let ownersArray = [ { name: 'Malcolm', pets: ['Bear', 'Minu'], }, { name: 'Caroline', pets: ['Basil', 'Hamish'], }, ];
const petArray = (owner, ownersArray) => {
let array = ownersArray.filter((arr) => arr.name===owner)
return array.length>0 ? array[0].pets : 'owner not found'
}
console.log(petArray("Caroline", ownersArray))