0

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]);
}
LMessing
  • 9
  • 3
  • Your function does pretty much nothing so far, do some research about how javascript loops work before asking a new question. – Adam Apr 05 '17 at 19:12
  • 1
    Possible duplicate of [From an array of objects, extract value of a property as array](http://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – Heretic Monkey Apr 05 '17 at 19:15

1 Answers1

2

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
kind user
  • 40,029
  • 7
  • 67
  • 77