Home > other >  Display data from a JSON file in a list, how to access parts in a Javascript object
Display data from a JSON file in a list, how to access parts in a Javascript object

Time:12-03

I have a validated JSON file with all the languages of the world. I am trying to populate a list on a Vue 3 app but cannot seem to get it right. My lack of experience forces me to ask how do I access the inner parts of an object.

JSON file (shortened):

[
    { "code": "ab", "name": "Abkhaz", "nativeName": "аҧсуа" },
    { "code": "aa", "name": "Afar", "nativeName": "Afaraf" },
    { "code": "af", "name": "Afrikaans", "nativeName": "Afrikaans" },
    { "code": "ak", "name": "Akan", "nativeName": "Akan" },
    { "code": "sq", "name": "Albanian", "nativeName": "Shqip" },
    { "code": "am", "name": "Amharic", "nativeName": "አማርኛ" },
    { "code": "ar", "name": "Arabic", "nativeName": "العربية" },
    { "code": "an", "name": "Aragonese", "nativeName": "Aragonés" }
]

Vue JS part that imports the JSON file and adds it to a list:

<script setup>
import { ref } from "vue";
import languages from '@/store/languages.json'
import axios from "axios";
const allLangauges = ref([languages])
</script>

Here is the part in the Vue app that is supposed to populate the div:

<div  v-if="fields.searching">
    <div >
        <div
            v-for="name in allLangauges"
            :key="name.id"
            :value="name.id"
            
        >
            <input type="checkbox" name="" id="" value="" />
            <h4>{{ name.name }}</h4>
        </div>
    </div>
</div>

If I console.log the response then I get the following: enter image description here

How do I access the name property of the inner array? I am still learning so want to know how to access the inner parts. Do I have to do languages._rawValue.name? or ['name'] or how?

What am I doing wrong and why can I not see a complete list with all the languages in the div?

CodePudding user response:

I don't know Vue, but if languages is already an array, why do you not pass directly to ref() ?

const allLangauges = ref(languages);

Then, when you iterate on language, you should have an object and not an array because it's looks like this (for me, if I understand):

[[{object}, {object}, ...]]

CodePudding user response:

Is this what you looking for display? do you forget to return the data? try my sample here >>> Sample

  • Related