1

I am using a for loop to display a list of items on my page. As you can see, each object is declared in my array.

const animals = [
  {
    name: "monkey",
    food: "fruit",
    img: "images/fruit.jpg",
  },
  {
    name: "horse",
    food: "hay",
    img: "images/hay.jpg",
  },  
  {
    name: "sealion",
    food: "fish",
    img: "images/fish.jpg",
  }
];

new Vue ({
  el: '#app',
  data: {
    zoo: animals
  }
});

The below code would print a list of animals and the food they like on a listings page.

<ul>
    <li v-for="(item, index) in zoo">
        <p>{{index }} {{ item.name }}</p>
        <p>{{index }} {{ item.food }}</p>
    </li>
</ul>

However, I also need to use the information stored in this array elsewhere on my site. But, this time not in a loop.

For a separate details page, I would need the information for only the third animal (index position 2)

<h2>My favorite animal is a {{ item[2].name }} and it eats {{ item[2].food }} </h2>

Is there a way to do this?

1
  • My favorite animal is a {{ zoo[2].name }} and it eats {{ zoo[2].food }}? Commented Jan 29, 2019 at 22:33

2 Answers 2

2

Your code will work and it's OK but to be more defensive it's good to create a method (or filter) to get a specific element from the Array, for method example:

methods: {
  getAnimalByIndex({ animals = [], index = 0 }) {
    return animals[index] || {}
  }
}

...and then use in template like below:

<h2>My favorite animal is a {{ getAnimalByIndex({ animals, index: 2 }).name }} and it eats {{ getAnimalByIndex({ animals, index: 2 }).food }} </h2>

Thanks to above you can provide fallback value or be sure that will be OK even if animals is undefined ;)

Moreover, if you want to get always third animal then maybe it's good idea to use computed value, like below:

computed: {
  thirdAnimal() {
    return this.animals[2] || {}
  }
}

...and use computed value in template:

<h2>My favorite animal is a {{ thirdAnimal.name }} and it eats {{ thirdAnimal.food }} </h2>
Sign up to request clarification or add additional context in comments.

1 Comment

This works fantastic so thank you very much. Really appreciate your help as now I understand.
0

You could create a computed property to return a specific object in the array. If the property is reactive, the computed will also be reactive and watch for updates to that property.

You could create a method to find a certain object in array, by index, or whatever you want i suppose:

computed: {
  sealion () {
    return animals[2]
  }
},
methods: {
  getAnimal (i) {
    return animals[i]
  },
  getAnimal (name) {
    animals.forEach((animal) => {
      if (animal.name === name) return animal
    }
  }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.