CodeCabin
CodeCabin

Reputation: 233

How do I select an Object based on the key value - VueJS

I have an object in Vuejs (see below). I want to select the email value ie: "[email protected]".

{
      "fields": [
        {
          "label": "email",
          "value": "[email protected]", 
        },
        {
          "label": "firstName",
          "value": "Foo", 
        },
        {
          "label": "lastName",
          "value": "Bar", 
        },
      ]
     }

I can do a

v-for(field in fields)

Then add an if statement to show only the email

<div v-if="field.label == 'email'">{{field.value}}</div>

But I was wondering if there was a better way to select the field based on a key's value without having to loop through the entire data object.

I tried unsuccessfully doing things like this:

fields(label, 'email')
// and
v-if fields.label == 'email'

Upvotes: 2

Views: 1797

Answers (2)

Phil
Phil

Reputation: 164730

One solution would be to create a computed map of field label to value

computed: {
  fieldMap () {
    return Object.fromEntries(this.fields.map(({ label, value }) => [ label, value ]))
  }
}

Then you can use

<div>{{ fieldMap.email }}</div>

If you're only wanting to work with this specific field, you can create a computed property to make access easier

computed: {
  emailField () {
    let field = this.fields.find(({ label }) => label === 'email')
    return field ? field.value : ''
  }
}

and then you can just use

<div>{{ emailField }}</div>

Upvotes: 1

Lachlan
Lachlan

Reputation: 1282

You could alternatively check if the current key being rendered has an index that matches the respective key with the 'email' label's own index.

Note that this will only work in this instance as we already know the exact values of the object.

<div v-for="(field, index) in fields" :key="index">
  <div v-if="index === 0">
    {{ field.value }}
  </div>
  <div v-else>
    Not email: {{ field.value }}
  </div>
</div>

Upvotes: 0

Related Questions