javascriptvue.jsvuejs3vuejs3-composition-api

Vue.js iterate complex object by data key


I'm using Vue.js 3 to build a simple article configurator.

Let's define a complex object:

const article = reactive({
  code: 'code',
  specs: {
    type: { text: 'description type', value:'mytype'} ,
    prop1: { text: 'description prop1', value: 'myprop1' },        
    prop2: { text: 'description prop1', value: 'myprop1' },                
  },
  dimensions: { base: 10, height: 20}
})

Let's see every article.spec:

<li v-for="(value, propertyName, index) in article.specs">
  {{ propertyName }}:  {{ value }} ({{ index }})
</li>

Result:

type: { "text": "description type", "value": "mytype" } (0)
prop1: { "text": "description prop1", "value": "myprop1" } (1)
prop2: { "text": "description prop1", "value": "myprop1" } (2)

But how do I extract property "value" only to get.

type: description type
prop1: description prop1
prop2: description prop1

I'v tried with:

{{ propertyName }}:  {{ value[text] }}  ({{ index }})

But result in empty values:

type: (0)
prop1: (1)
prop2: (2)

Solution

  • Another approach to minimize template code could be to define a computed:

        const article_specs = computed(() => {
          let result = '';
          Object.keys(article.specs).forEach((item) => {
        
            result +=  article.specs[item].value + 'todo'
            console.log("item", article.specs[item])
        
          })
    
      return result;
    })
    

    And template code became:

    {{article_specs}}