Search code examples
javascriptvue.jsvuejs2vue-componentv-for

Iterate over array in v-for without knowing key-value pair beforehand


I have an array of objects like this:

[ { Articulo: "Producto 1", Precio: "2.95" }, { Articulo: "Producto 2", Precio: "2.95" }  ]

I want to use a v-for loop to iterate through the objects in order to display a div with text like this:

Articulo -> Producto 1

Articulo -> Producto 2

However, since the array is autogenerated from a function I don't know the key / value pairs beforehand, so I don't know how can I show that info in my template.

Any idea how I can approach this?


Solution

  • If you only the want the first property, you could do this:

    new Vue({
      el: "#app",
      data() {
        return {
          arr: [
            { Articulo: "Producto 1", Precio: "2.95" },
            { Articulo: "Producto 2", Precio: "2.95" }
          ]
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <div v-for="obj in arr">
        {{ Object.keys(obj)[0] }} -> {{ Object.values(obj)[0] }}
      </div>
    </div>

    (There used to be no guarantee of property order in JavaScript for ensuring you get Articulo instead of Precio, but pretty sure that's a non-issue nowadays and especially with Vue CLI.)

    If you want all properties, you can loop over the object key/value pairs:

    new Vue({
      el: "#app",
      data() {
        return {
          arr: [
            { Articulo: "Producto 1", Precio: "2.95" },
            { Articulo: "Producto 2", Precio: "2.95" }
          ]
        }
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <div v-for="obj in arr">
        <div v-for="(value, key) in obj">
          {{ key }} -> {{ value }}
        </div>
      </div>
    </div>