编写一个函数,将一个对象数组作为参数,并返回对象名称的数组。然后,将该数组记录到控制台

时间:2017-04-05 19:09:05

标签: javascript arrays object

我正在研究javascript数组,需要编写一个函数,该函数接受下面数组的第一个索引,并返回对象名称的数组。

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'
  },

]

这是我的功能:

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

1 个答案:

答案 0 :(得分:2)

您可以使用Array#map仅返回每个对象的名称。

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