menu

Questions & Answers

Vue.js array in object from db is undefined, even though the values appear in console

i'm trying to get data from db and show it on the screen. I get the data using axios, i got the response successfully. So, i use forEach to get arrays inside the data.

 mounted(){
    axios.get('/api/tree').then(Response => {
                var datas =Response.data.trees

                datas.forEach(function(data){
                    var tree = data.tree
                    console.log(tree)
                    console.log(tree.nodes)
                })
    })

}

the data is as below.

{
    'id' : "aeENkvQdx",
    'tree': {  
         'nodes' : [{ 'node_id': 0, 'text': 'test'}, .....],
         'edges' : [{ 'node_id': 0, 'text': 'test'}, .....]
     }

}

so, when i print console.log(tree) it's working fine. It shows { 'nodes' : [...,..,], 'edges: [...,...,...]}. However, when i print console.log(tree.nodes) or console.log(tree.edges), then it shows an error saying TypeError: Cannot read properties of undefined (reading 'nodes') or 'edges', even though it prints the values of nodes or edges array in the console. I have no idea why it only causes error when i try to access nodes or edges, and how to solve this issue...

Comments:
2023-01-20 23:20:11
I think you need to do console.log(tree.tree.nodes); - It usually makes it clearer when your parent variable is not name of one of your properties, and you end up getting clearer errors.
Answers(1) :

It is happening because in some of the data objects, tree property is missing. Hence, when you trying to access nodes or edges objects it is giving you the below error.

TypeError: Cannot read properties of undefined (reading 'nodes') TypeError: Cannot read properties of undefined (reading 'edges')

You can resolve this by using Optional Chaining (?.) operator.

console.log(tree?.nodes)
console.log(tree?.edges)

Live Demo :

const datas = [{
  'id' : "aeENkvQdx",
  'tree': {  
    'nodes' : [{ 'node_id': 0, 'text': 'test'}],
    'edges' : [{ 'node_id': 0, 'text': 'test'}]
  }

}, {
  'id' : "aeENkdYJh"
}];

datas.forEach(function(data) {
  var tree = data.tree;
  console.log(tree);
  console.log(tree?.nodes);
});