Home > Net >  How to display text in HTML from an array?
How to display text in HTML from an array?

Time:09-11

I have a project that I am working on. I call my Django API and I get a ManyToMany array back as seen below.

[
{"interest_name":"Money"},
{"interest_name":"Django"},
{"interest_name":"Test"}
]

What is the best way to display the below in HTML as:

Money
Django
Test

Instead of

[
{"interest_name":"Money"},
{"interest_name":"Django"},
{"interest_name":"Test"}
]

I am trying to pass the above into an HTML element and display on the frontend. Any and all help is appreciated! EDIT

Here is my full code.

<template>
  <div >
    </div>
     <div >
        <div >
            <div v-for="projects in ProjectsAPI" :key="projects.id" >
        <div >
        <div ><strong>Task Made By: {{ projects.project_title }}</strong></div>
        <div >
            <div>
                <h5 >{{projects.project_description}}</h5>
                <p>{{projects.interest_category}}</p>
            </div>
        </div>
        <div >
            Task Made At: {{projects.created_at}}
        </div>
    </div>
    </div>
        </div> 
     </div> 
</template>

<script>
import { getAPI } from '../../axios-api'

export default {
    name: 'ProjectDashboard',
    data () {
      return {
        ProjectsAPI: []
      }
    },
    created () {
      getAPI.get('api/v1/projects')
      .then(response => {
        this.ProjectsAPI = response.data
        console.log('API Data Received')
      })
      .catch(err => {
        console.log(err)
      })
    }
}
</script>

Since projects.interest_category is the only JSON array how would I get the

Money
Django
Test

To show instead of?:

[
{"interest_name":"Money"},
{"interest_name":"Django"},
{"interest_name":"Test"}
]

CodePudding user response:

If I understood you correctly try with inner v-for:

new Vue({
  el: '#demo',
  data() {
    return {
      ProjectsAPI: [{project_title: 'aa', project_description: 'desc', interest_category: [{"interest_name":"Money"}, {"interest_name":"Django"}, {"interest_name":"Test"}]}]
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="projects in ProjectsAPI" :key="projects.id" >
     <div >
        <div ><strong>Task Made By: {{ projects.project_title }}</strong></div>
        <div >
          <div>
            <h5 >{{projects.project_description}}</h5>
             <p v-for="(cat, i) in projects.interest_category" :key="i">{{ cat.interest_name }}</p>
          </div>
        </div>
    </div>
  </div>
</div>

CodePudding user response:

Basically, a loop.

var obj = [
  {"interest_name":"Money"},
  {"interest_name":"Django"},
  {"interest_name":"Test"}
]

document.querySelector("pre").innerText = Object.values(obj).map(i => i.interest_name) .join("\n")
<pre></pre>

  • Related