0

I have an array which is:

enter image description here

And I want to make a foreach loop and list all key's & script_content's to the view.

My vue components 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!',
                });
            });
    },

component data:

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

I am able to display the values of the first array, but don't know how to make a foreach loop in an associative array.

HTML:

    <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 goal is to list all key's and script_content's in a HTML list or a div.

Any help will be appriciated.

2 Answers 2

1

You can just use codes below:


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

...
for (let index in data) {
   this.keys.push(data[index].key);
   this.contents.push(data[index].script_content);
}
...

Then you can use v-for in html codes to use keys and contents.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Where this for statement should be placed? In mounted method?
@ViktorasssIT Yes, you can place it in mounted method.
Thanks, but the solution was this: this.scripts.forEach(function (script) { });
1

You should store all scripts into the data, not just data.scripts[0], and then iterate over them in the template using v-for directive. Here is a couple of good examples:

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

Comments

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.