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
}
2
  • 5
    Possible duplicate of Loop through an array in JavaScript Commented Jul 8, 2019 at 0:17
  • no it's not the same case Commented Jul 8, 2019 at 1:46

1 Answer 1

1

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

getNameList(){
  return this.fruits.map(fruit => fruit.name)
}

Sign up to request clarification or add additional context in comments.

4 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.