2

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'

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Sweet, looks good to me, works a charm. Thanks for the quick reply @Phil
0

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>

1 Comment

Would work but I don't always know the index of email.

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.