0

I want to make a method with vuejs that loop through an array of object and give me all the names in that array, but i dont know how

the method will be something like this:

fruits =[
  {name: "apple", calories: "50"},
  {name: "apple", calories: "100"},
];
methode(){
  var names = ''
  foreach(fruit in this.fruits){
     names = names+friut.name
  }
  return names
}

1 Answers1

1

fruits =[
  {name: "apple", calories: "50"},
  {name: "apple", calories: "100"},
];

getNameList(){
  return this.fruits.map(fruit => fruit.name)
}
aquilesb
  • 2,182
  • 1
  • 19
  • 19
  • it works but it gives me result like this **[ "apple", "tag apple" ]** but i want it like this: **apple,apple** not in a array –  Jul 08 '19 at 02:02
  • Just add a `.toString()` in the end. `getNameList(){ return this.fruits.map(fruit => fruit.name).toString() }` – aquilesb Jul 08 '19 at 02:10
  • it works just fine but in the console it gives me this error **TypeError: Cannot read property 'map' of undefined"** –  Jul 08 '19 at 02:21
  • The error message says everything, you are sending an undefined object to this function. Double check your array. – aquilesb Jul 08 '19 at 02:44