List of strings that have been processed after completing the loop and returning the

I am looking to display multiple values on separate lines in a Vuetify snack bar. I have an object and I would like to show key value pairs individually like this:

Brand: Porsche

Model: Cayman

Currently, the format is:

Brand: Porsche, Model: Cayman

Visit my CodePen example for reference.

This is the function code that I am using:

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    multiLine: true,
    snackbar: false,
    text: 'I\'m a multi-line snackbar.',
  }),

  methods: {
    getResult(){
      const object = {brand: ['Porsche'], model:['Cayman']};
      let result = [];
      for (let [key, value] of Object.entries(object)) {
           result.push(`${key}: ${value}`);
      }
      console.log(result);
      this.text = result;
      this.snackbar = true;
    }
  }
})

Answer №1

Here are a few errors that need to be corrected:

  1. method: should actually be methods:
  2. The function result.push will not work if result is not initialized as an Array. You must initialize it using [].
  3. When using {{text}} in the template, VueJS cleanses the value to remove any HTML content. If you require HTML for line breaks, then you should utilize the v-html attribute instead (as shown in the code snippet below).
  4. If you display an Array (result), it will automatically convert to a string separated by commas. To avoid this and display with line breaks, you need to construct the string manually using result.join('<br>').

View the fixed demo (also available on Codepen):

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data: () => ({
    multiLine: true,
    snackbar: false,
    text: 'I\'m a multi-line snackbar.'
  }),

  methods: {
    getResult(){
      const object = {brand: ['porsche'], model:['Cayman']};
      let result = [];
      for (let [key, value] of Object.entries(object)) {
        result.push(`${key}: ${value}`);
      }
      console.log(result);
      this.text = result.join('<br>');
      this.snackbar = true;
    }
  }
})
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/@mdi/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bddbd2d3c9fd8993c5">[email protected]</a>/css/materialdesignicons.min.css" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a5c5f4f5e434c536a180452">[email protected]</a>/dist/vuetify.min.css" rel="stylesheet">    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9fe9eafadfadb1e7">[email protected]</a>/dist/vue.js"></script>    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d7b786879646b744d3f2375">[email protected]</a>/dist/vuetify.js"></script><style>.as-console-wrapper{display: none!important}</style>
 
<div id="app">
  <v-app id="inspire">
    <div class="text-center">
      <v-btn dark color="red darken-2" @click="getResult">
        Open Snackbar
      </v-btn>
      <v-snackbar v-model="snackbar" :multi-line="multiLine">
        <div v-html="text"></div>
        <v-btn color="red" @click="snackbar = false">
          Close
        </v-btn>
      </v-snackbar>
    </div>
  </v-app>
</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

Access the current slide number with the slideNumber feature in Reveal.js

Can someone assist me with Reveal.js? Could you explain how I can retrieve the current slide number and store it in a variable? I am looking to add an event on my fourth slide. Thank you for your help! ...

Switch between Light and Dark Modes effortlessly with just one button

I've created a code that effortlessly switches between light mode and dark mode with the press of buttons. However, I'm looking to combine these two functionalities into a single toggle button for ease of use. If anyone can provide insight on how ...

What seems to be the issue with loading this particular file into my JavaScript code?

When attempting to import a file into my code, I encountered an issue where the folder could not be found. Interestingly, when manually typing out the folder name, it is recognized and suggested by the system. Even providing the full path did not yield dif ...

Numeric keypad causing issues with setting minimum and maximum lengths and displaying submit button

I designed a password pin page that resembles a POS NUMPAD for users to enter their password. I am struggling to make the condition specified in the JavaScript function properly. Rule: Hide the submit button if the minimum input is less than 4 characters ...

Display a helpful tooltip when hovering over elements with the use of d3-tip.js

Is it possible to display a tooltip when hovering over existing SVG elements? In this example, the elements are created during data binding. However, in my case, the circles already exist in the DOM and I need to select them right after selectedElms.enter ...

Simultaneously updating the states in both the child and parent components when clicked

In my code, I have two components: the parent component where a prop is passed in for changing state and the child component where the function is called. The function changes the state of the parent component based on an index. changeState={() => this ...

Tips for validating an email address using ReactJS

I'm currently working on customizing the email verification process for a signup form in ReactJS. My goal is to replace the default email verification with my own validation criteria. Initially, I want to ensure that the entered email address contains ...

Bringing in a variable from a React component to a JavaScript file

I've created a React component called Button with two states named name and players. Now, I need to access these states in a separate JavaScript file that is not a component. Below are the relevant code snippets: Button.js import {useState} from &qu ...

building CharFields dynamically in Django

I am looking to gather input from the user using CharField. Using the value entered in CharField, I want to generate the same number of CharFields on the same page. For example, if the user enters "3" and clicks OK, it should display "3" CharFields below ...

Is there a method to obtain the image path in a similar manner to item.src?

I am currently utilizing freewall.js, which can be found at The images will be generated dynamically. Therefore, the HTML structure will look like this: <div class="brick"> <img src="" width="100%"> </div> Here is the corresponding J ...

Input ENTER triggered JSON path loading

Upon clicking "enter", I am looking to display the description corresponding to the title. To achieve this, I have defined a variable to store the path of the description: var descri = json.query.results.channel.item.map(function (item) { return item. ...

What is the process of directing to another HTML page within the same Express controller script?

I am looking to switch the initial page (login page) to a second page (admin dashboard) from within the same controller in Express after a specific action has been taken. Here is the relevant code snippet from my controller file nimda.js: function handle ...

Encountering npm error code 1 during npm installation in a Vue.js project

Recently, I installed VueJS Material Dashboard (with Laravel), but encountered an issue with the npm install command on this VueJS template. The error message displayed was related to gyp and python39. Even when running the node.js command prompt as admini ...

Convert a pandas dataframe into a JSON object with nested structures

Someone raised a similar question in a different forum, which was expertly answered by user1609452 using R. However, I believe there is more to explore with this topic. Let's consider a table (MyData) that looks like this: ID Location L_size L_co ...

Tips on displaying a message when search results are not found

import React, { useState, useEffect } from 'react' import axios from 'axios' function DataApi({ searchTerm }) { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useSta ...

Keeping Vuex state in harmony with Firebase

When it comes to keeping my Vue.js state in sync with Firebase, I have implemented a strategy that involves setting up references to Firebase, getters, mutations, and actions in a separate folder within the store. So far, everything seems to be working fin ...

Securing Azure B2C user access with Auth Flow using PKCE, MSAL v2, Vue.js, & Azure Functions

Our application utilizes Vue.js, Azure B2C Tenant, and Azure Functions (C#) to authenticate users. We implement the Auth Flow with PKCE and utilize the MSAL v2 library on the front-end, specifically the npm package @azure/msal-browser for MSAL. The challe ...

The HiddenField is returning empty when accessed in the code behind section

In my gridview, the information is entered through textboxes and saved to the grid upon clicking a save button. One of these textboxes triggers a menu, from which the user selects a creditor whose ID is then saved in a HiddenField. <td class="tblAddDet ...

Discover the secret to restricting JSON API functionality in your WordPress plugin

I am interested in using WordPress to build a website, specifically looking to export site posts using the JSON API. However, I encountered an issue when attempting to limit the displayed posts by category. Clicking on the "get_category_posts" link within ...

Setting the UrlAction in an Asp.Net Core Controller: A step-by-step guide

There is an input box for searching on the website... The following HTML code snippet shows how the search functionality is implemented: <form id="searchForm" asp-controller="Product" asp-action="SearchProduct" method=&quo ...