首页 > 解决方案 > Can't access object properties even though I can see they exist

问题描述

I can't access any of the object properties, keep getting undefined.

I have tried

console.log(JSON.parse(this.$store.state.user.userId));

and

console.log(JSON.parse(this.$store.state.user[0].userId));

When I do

console.log(JSON.parse(this.$store.state.user.userId));

I get

"SyntaxError: Unexpected token u in JSON at position 0"

When I just do

 console.log(JSON.parse(this.$store.state.user));

I get the object and I can see the properties. It's just that whenever I try to access them I get undefined.

标签: javascriptvue.js

解决方案


When I just do console.log(JSON.parse(this.$store.state.user)); I get the object and I can see the properties.

This means that this.$store.state.user contains JSON string which describes the user object.

Thus JSON.parse(this.$store.state.user.userId) is incorrect. In this case you are trying to get property userId from string, getting undefined and JSON.parse function fails on the first symbol, which is 'u'.

You should use JSON.parse(this.$store.state.user).userId instead.


推荐阅读