Home > Enterprise >  Returning an array of all the pet names
Returning an array of all the pet names

Time:05-23

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! :)

CodePudding user response:

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);

CodePudding user response:

Try this methods map() and flat()

Example code:

const arr = [
    { name: 'Malcolm', pets: ['Bear', 'Minu'], },
    { name: 'Caroline', pets: ['Basil', 'Hamish'], }
];

let res = arr.map(x => x.pets).flat();

console.log(res);

CodePudding user response:

let ownersArray = [ { name: 'Malcolm', pets: ['Bear', 'Minu'], }, { name: 'Caroline', pets: ['Basil', 'Hamish'], }, ];

const petArray = (owner, ownersArray) => { return ownersArray.fillet ownersArray = [ { name: 'Malcolm', pets: ['Bear', 'Minu'], }, { name: 'Caroline', pets: ['Basil', 'Hamish'], }, ];

const petArray = (owner, ownersArray) => { return ownersArray.filter((arr) => arr.name===owner)[0].pets

} console.log(petArray("Malcolm", ownersArray))ter((arr) => arr.name===owner)[0].pets

} console.log(petArray("Malcolm", ownersArray))

  • Related