What is the best way to showcase the contents of an associative array using Vue.js?

I have a variable that contains an array:

https://i.sstatic.net/OQfB9.png

My goal is to create a foreach loop and display all the key's and script_content's in the view.

This is my Vue component's mounted method:

mounted() {
        this.loading = true;
        axios.get('/app/json-ld/json-ld-settings')
            .then(res => {
                let data = res.data;
                console.log(data.scripts);
                this.key = data.scripts[0]['key'];
                this.scriptContent = data.scripts[0]['script_content'];
            })
            .catch(error => {
                this.loading = false;

                this.$notify({
                    group: 'notify',
                    type: 'error',
                    text: 'Something happened! Please refresh the page and try again or contact support!',
                });
            });
    },

Here is the structure of the component data:

data: () => ({
        errors: {},
        key: [],
        scriptContent: [],

While I can display values from the first array, I am unsure of how to utilize a foreach loop with an associative array.

Here is the HTML structure:

    <div class="py-3 d-flex flex-row justify-content-end align-content-end">
        <div class="pr-2">
            <h5>Key</h5>
            <span>{{key}}</span>
        </div>
        <div class="pl-2">
            <h5>Script content</h5>
            <span>{{scriptContent}}</span>
        </div>
    </div>

The ultimate objective is to list all the key's and script_content's within an HTML list or div.

Any assistance would be greatly appreciated.

Answer №1

If you want to implement this functionality, you can follow the code snippets provided:


data() {
   return {
     keys: [],
     contents: [],
  }
}

...
for (let i in dataSet) {
   this.keys.push(dataSet[i].id);
   this.contents.push(dataSet[i].content);
}
...

After adding the data to the arrays, you can utilize v-for in your HTML code to iterate over the keys and contents as needed.

Answer №2

To ensure efficient data management, it is recommended to store all scripts within the data object instead of just data.scripts[0]. By doing so, you can iterate over them in the template using the v-for directive. Check out these helpful examples for more insight:

https://v2.vuejs.org/v2/guide/list.html

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

Error is being returned by the JSONP callback

Looking to grasp JSONP. Based on my online research, I've gathered that it involves invoking a function with a callback. Other than that, is the way data is handled and the data format similar to JSON? I'm experimenting with JSONP as shown below ...

Error: Popper is not found in the Bootstrap bundle even after importing it

Having some issues with bootstrap4. I have imported the bootstrap.bundle.js which includes popper.js. Despite this, I keep encountering the following error: Uncaught ReferenceError: Popper is not defined This is how I've included the scripts: < ...

Error occurred during npm build with Browserify: Module not found

When I run npm build with the following command: "build": "browserify -t [ babelify --presets [ es2015 react ] ] app/assets/app.jsx -o public/javascripts/app.js" I encounter the error message below: Error: Cannot find module 'components/maininput.j ...

Mastering the art of rendering child routes in Vue.js involves utilizing the $router.push method effectively

I designed a Vue component called Layout with two distinct named views: <template> <router-view name="navigation"></router-view> <router-view name="content"></router-view> </template> Here is my router outline: ex ...

Recursively toggle child elements using JQuery

My knowledge of JQuery is limited, so here's the issue I'm facing. Below is an example of the HTML structure: <ul class="first-class"> <li class="second-class"> <a href="#_"> <i class="fa fa-plus"></i& ...

Troubleshooting Route Rendering Issues with React Router Dom and Loading Components

I am currently developing a React project and focusing on the navbar element. As part of this, I am integrating the react-router-dom into the project. The <Route/> is nested within the <Routes/>, all encapsulated by the <BrowserRouter/>. ...

Verify Session Cookies through JSONP requests

I've developed a bookmark that pulls all images from a webpage upon clicking and sends the image's src back to another server using JSONP. Challenge: The remote server must validate session authentication cookies to confirm that the user sending ...

The website becomes unresponsive and locks up after being on the same page for several

We are dealing with a PHP web application that heavily utilizes javascript and jquery. The main issue we are facing involves a create/read/update/delete page where users can modify content. These modifications occur using AJAX, which prevents a full page r ...

selecting the ajax url for the datatable

I need to select the datatable ajax URL based on whether it contains data1, data2, or data3. Below is my code snippet: $(document).ready(function() { var $table = $('#datatable1'); $table.DataTable({ "columnDefs": [ ...

Having Trouble Concealing an Element with jQuery UI

I am attempting to implement a jQuery slide effect where pressing a button causes the first paragraph tag to slide out of view and the second paragraph tag to slide into the viewport. Despite utilizing jQuery UI for the slide effects, I am encountering dif ...

Error: The module was not found. Unable to locate 'bundle.js' within the directory path '/Users/jonathankuhl/Documents/Programming/node js/sandbox/webpack-app'

I am currently following a basic tutorial on Webpack, but I am facing difficulties in compiling a simple one-line JavaScript application. Despite installing and uninstalling it multiple times, the compilation process seems to be unsuccessful. This tutoria ...

Struggling to toggle the visibility of a table with a button - successfully hiding it, but unable to make it reappear?

I need a button that can toggle (show/hide) a table. Currently, my code hides the table successfully, but it fails to show the table again when I click the button. It seems like there is an issue with refreshing or redirecting after clicking the button for ...

Angular FlexLayout MediaObserver: How to determine the active width using a specific div?

I am currently working on customizing the behavior of fxFlex. The web application I am working on has the capability to function as a standalone version, occupying the full screen of a web browser, as well as being embedded as a web component. It is design ...

How is it possible that this event listener is able to capture an event that was already sent before it was

I am facing an issue with my Vue JS code. When I click on the account <a> tag, it triggers the toggle method. The toggle method adds an event listener to the document. However, as soon as the toggle method is executed, the event listener fires and ...

The code encountered an error with message TS2345 stating that the argument type '(a: Test, b: Test) => boolean | 1' cannot be assigned to a parameter type of '(a: Test, b: Test) => number'

Apologies for the lengthy subject, but I am having trouble understanding the response. Here is my code snippet: this.rezerwacjeFilteredByseaarchInput.sort(function (a, b) { if (a[5]===null) { // console.log(a[5]); return 1; } ...

Why are JS & jQuery's inArray() and indexOf() functions not functioning correctly when indexes are strings?

Here is an example of an array: var arr = []; arr['A string'] = '123'; arr['Another string'] = '456'; I am attempting to find the index of either '123' or '456'. Both methods below are returnin ...

Create a receipt by utilizing jQuery with dynamically generated inputs

Is there a way to insert the descriptions and amounts of invoice items into the receipt, similar to the due date? The input for this section is dynamic with multiple rows that can be added or deleted. I'm considering using a counter that increments e ...

I am experiencing an issue with the functionality of Handlebars registerPartial()

Check out my code snippet on JsFiddle Error Message: Uncaught Error - The partial social could not be found Note: I have made sure to include all necessary libraries. Looking forward to your assistance. Thank you! ...

Generate a PDF document from a selection of table rows using the pdfmake library in Vue-tables-2

Searching for a way to generate a pdf of multiple selected rows in vue-tables-2, I came across the pdf library called pdfmake which seems promising. As someone new to this concept, I'm having difficulty figuring out how to: Integrate it into a vue-t ...

Why does the styling of the inner Span adhere to the style of the outer Span?

How can I adjust the opacity of the color "blue" to 1 in the code snippet below? <!DOCTYPE html> <html> <body> <p>My mom's eyes are <span style="color:blue;font-weight:bold;opacity:0"> <span style="color:blue;fo ...