简体   繁体   中英

write a function that takes an array of objects as a parameter and returns an array of the objects' names. then, log that array to the console

I'm working on javascript array and need to write a function that takes the first index of the array below and returns an array of the objects' names.

var animals = [
  { 
    name: 'murphy brown the dog',
    type: 'dog',
    age: 4,
    fav_toy: 'squeaky octopus'
  },
  { 
    name: 'mervin',
    type: 'cat',
    age: 1,
    fav_toy: 'catnip mouse'
  },
  { 
    name: 'peppercorn',
    type: 'cat',
    age: 3,
    fav_toy: 'lady bug pillow'
  },
  { 
    name: 'willa',
    type: 'cat',
    age: 4,
    fav_toy: 'jingle ball'
  },

]

Here's my function:

function getName(animals){
  console.log(animals[0]);
   return (animals[0]);
}

You could use Array#map to return just the names from each object.

 var animals = [{name:"murphy brown the dog",type:"dog",age:4,fav_toy:"squeaky octopus"},{name:"mervin",type:"cat",age:1,fav_toy:"catnip mouse"},{name:"peppercorn",type:"cat",age:3,fav_toy:"lady bug pillow"},{name:"willa",type:"cat",age:4,fav_toy:"jingle ball"}], res = animals.map(v => v.name); // ---> return only the name value of each object console.log(res); // ---> log the result to the console 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM