Ryan H
Ryan H

Reputation: 2955

Vue JS access object by dynamic key within object

I've got a v-for loop in Vue JS 2.x that loops over an Array of objects, each object in the array has a "key", basically like a name, but it's dynamic, and isn't going to be consistent. I'm trying to access the data associated with that key so that I can display information from my v-for loop, here's what my data looks like in my array...

[{
  "6457": {
    "agent": {
      "id": 4003,
      "memFree": 0
    }
  }
}, {
  "7809": {
    "agent": {
      "id": 7809,
      "memFree": 20
    }
  }
}]

I was hoping I could just access the key by using [0], but that doesn't seem to return anything in this case.

<div v-for="(server, index) in servers" :key="index">
  <!-- gives me a single object by key -->
  {{ server }}

  <!-- doesn't work -->
  {{ server.memFree }}

  <!-- doesn't work -->
  {{ server[0].memFree }}
</div>

What am I missing here?

Upvotes: 1

Views: 2512

Answers (2)

Mocuishle
Mocuishle

Reputation: 174

<div v-for="(server, index) in servers" :key="index">
  {{ Object.values(server)[0].agent.memFree }}
</div>

Upvotes: 2

Amaarockz
Amaarockz

Reputation: 4684

Modify your template to be

<div v-for="(server, index) in servers" :key="index">
  <div v-for="(agentData, property) in server" :key="property">
    {{ agentData.agent.memFree }}
  </div>
</div>

Upvotes: 1

Related Questions