Looking for a way to choose an Object using the key value in VueJS?

In my Vuejs setup, there is an object containing various fields including an email value which looks like this: "[email protected]".

{
      "fields": [
        {
          "label": "email",
          "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e3831311e3c3f2c703d3133">[email protected]</a>", 
        },
        {
          "label": "firstName",
          "value": "Foo", 
        },
        {
          "label": "lastName",
          "value": "Bar", 
        },
      ]
     }

One possible way to extract the email field only is by using a v-for loop and adding a conditional statement.

v-for(field in fields)

We can then check if the label matches 'email' and display its value.

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

However, I am looking for a more efficient method to directly select the email field without looping through the entire object.

I've attempted approaches like:

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

Answer №1

To simplify the process, consider creating a computed map that links field labels with their corresponding values

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

You can then access specific fields like this:

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

If you're primarily working with one field, create a computed property for easier access

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

You can then display the field using:

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

Answer №2

To determine if the key currently being displayed corresponds to the 'email' label's own index, you can utilize a conditional check.

It is important to note that this approach will only be effective in this specific scenario where we are already aware of the object's precise values.

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery for client-side validation when the user clicks a button in an ASP.NET application

My goal is to implement field validation on button click using Jquery, but I'm facing an issue where it seems like the code behind event and the jQuery event are executing simultaneously. (UPDATED) <asp:Button ID="btnsave" runat="server" ClientI ...

Scrolling Down on a Jquery Login Page

I am currently utilizing JQuery version 1.4.2. My objective is to allow the user to scroll down to the login form by clicking on the 'login' option in the top menu, similar to Twitter's design. The implementation works impeccably with insert ...

What's the best way to ensure an endless supply of copied elements with identical classes to the clipboard?

Here is a snippet of my HTML code: <Div Class='POSTS'> <Div Class='POST'> <Div Class='CONTENT'>Text1</Div> </Div> <Div Class='POST'> <Div Class=&apos ...

Create a custom JavaScript library by incorporating an external library into it as a bundle

As I work on developing a library, one of the dependencies I plan to use is fabricjs. Installing fabricjs involves specific libraries and versions that can be cumbersome for users. Despite successfully installing it in my project and using it, my concern l ...

Executing Code Upon Module Load and Presenting It as Middleware

I am currently delving into the intricacies of how exporting and importing modules function in Nodejs. One of my tasks involves using a specific file to seed a mongodb database. Surprisingly, this file operates flawlessly and delivers the desired results ...

The Vue.js Vuetify.js error message is saying "A mystery custom element: <v-list-item>, <v-list-item-title> - Have you properly registered the component?"

I followed the instructions from Vuetify Data Iterator Filter section I am able to use various Vuetify components like v-btn, v-card, v-data-table, v-data-iterator, and more. However, I encountered errors only with <v-list-item> and <v-list-item ...

Configuring vue-jest: Does anyone know how to set up aliases for template/script src attributes in Vue?

Dependencies: "@vue/cli-plugin-unit-jest": "^4.5.13", "@vue/test-utils": "^1.2.1", "vue-jest": "^3.0.7" I am dealing with an application that utilizes an alias (referred to as "foo") de ...

Updating the color with the help of useState in React, with the use of Material

I enjoy changing the color of the icon with a click using a useState hook. I have added a click handler to the icon for this purpose. Below is the code snippet: import React, { useState } from 'react'; import './App.css'; import ThumbU ...

Prevent clicks from triggering on dynamically loaded ajax content within a DIV

I am seeking help on how to prevent click events from being triggered on dynamically loaded content within a specific DIV element. <div id="left_column"> <div class="menu">------</div> <div class="menu">------</div> ...

I rely on the handleChange function to update the state value, but unfortunately, it remains unchanged

In my project, I am working on creating multiple responsive forms (form1, form2, and form3) within the same page using framer motion. However, I am facing an issue where the state value is not updating correctly when users fill out the form. Specifically, ...

Issue encountered when utilizing ngResource in factory: unable to choose JSON index

ngResource in a factory is functioning properly, but unfortunately, it is only able to select the index of the JSON. However, it is also possible to bind the same variable $scope.resultItems. The console log appears as follows ...

Converting JSON data into a JavaScript array and storing it in a variable

Currently, I am delving into the world of JavaScript and my instructor has assigned a task that involves utilizing information from a JSON file within our JavaScript code. The issue I'm facing is deciphering how to effectively convert the JSON data i ...

Tips on storing the amount of time a user devotes to answering questions on my form into a database

I am facing an issue with storing the "duration" in my database. The "duration" I aim to store is the time spent by the user answering a question I created. When they click the submit button, I want to save the duration they spent in the database. Below i ...

Send an object to query when using Router.push in Next.js

Just getting started with NextJs and I'm experimenting with passing an object to another page through a component. Let me show you the code and explain what I'm attempting to accomplish: The object I want to pass looks like this: objectEx = { ...

Encountered an error in React where the declaration file for a module could not be located

New to Typescript and trying to incorporate a splitter into my project. I'm utilizing SplitPane from "react-split-pane/lib/SplitPane" and Pane from "react-split-pane/lib/Pane" in my Typescript project, but encountering an error: Could not find a de ...

Struggling to incorporate a logic in ajax using Cakephp2

I have a website built on CakePHP2 and I am looking to incorporate an Ajax function that will redirect to another URL if a specific PHP condition is met. Otherwise, it should display an error dialog. The tutorials I found on Google are quite complex for me ...

What is the method for accessing a map that has been set in a separate component?

My current setup involves utilizing a Leaflet map with vue2leaflet. The process I follow is quite standard: I import a list of places from a REST Api in the app store (vuex) Following that, during map initialization, the markers are created using the in ...

drag and zoom feature similar to Google Maps

Is it possible to create draggable effects similar to Google Maps on a group of div elements? Are there any JavaScript libraries available that can replicate this functionality? ...

The issue of variable stagnation in Firefox content script while utilizing self.port.on

I'm having trouble updating the version var as intended. When I try to update it with the following code: self.port.on("get-version", ver => { version = ver; alert(version); }); An alert pops up displaying the correct version number, but the HTML ...

What steps should I follow to create a Lunr search functionality for Markdown MD files?

Currently, I am in search of a suitable lunr search implementation for my MD (Markdown) documents spread throughout my React/NextJS website. Our website contains a plethora of Markdown docs within both blog and regular "docs" sections, necessitating a robu ...