[Vuejs]-I want simple array not [__ob__: Observer]

0👍

thank you all, finally i managed to solve it

first i extract array from vue’s [ob: Observer]

this.programming_languages = JSON.parse(JSON.stringify(response.data));

special thanks to @stockafisso

and second was that i couldn’t get this programming_languages array out of axios method, that happens due to nature of asynchronous call, see this informative link

How do I return the response from an asynchronous call?

i managed to solve it this way, async and await

methods: {

 async getPosts(){
           
          await axios.get('/api/hangman').then(response => {
                   this.programming_languages =  JSON.parse(JSON.stringify(response.data));
             
            }).catch(error => console.log(error));
        },
        
        randWord(){
            
        this.answer = this.programming_languages[Math.floor(Math.random() * this.programming_languages.length)].name;
        this.maxWrong = this.answer.length;
        },
},

 created(){
            
          this.getPosts().then(() => this.randWord());
                                
      }

0👍

most probable the error(s) is here:
this.programming_languages.push(JSON.parse(JSON.stringify(response.data)));

you are inserting the Laravel returned array inside the declared programming_languages, while you should override or concat it.
To explain better, a little example:

consider this:

let arr1 = [];
let arr2 = [1,2,3];

if you do arr1.push(arr2) your arr1 will be [[1,2,3]] while you want it to be [1,2,3].

Going back to your problem, to fix it you have two ways:

a)

.then((response)=> { 
                 this.programming_languages = JSON.parse(JSON.stringify(response.data));

b)

.then((response)=> { 
let swapArray = [...this.programming_languages];
this.programming_languages = swapArray.concat(JSON.parse(JSON.stringify(response.data)));

If this does not fix the error,
it could be the problem is in the array returned from Laravel. If it has not numeric or not sorted keys, JS will "fill" the missing spaces with Ob. Observer to try to keep the keys.

Leave a comment