我正在尝试从对象中获取价值。
当我执行与此调查相关的用户console.log(poll.user)
时
首先得到未定义,然后
{_id: "5bd99816068dee45fddf317e", username: "Karolina"}
我对_id
所以我尝试使poll.user._id
变得不确定。...
但是如果我在poll.user上使用for in
,则它具有值
PS投票将作为道具
致谢
投票价值
date: "2018-10-31T11:55:27.343Z"
options: (2) [{…}, {…}]
question: "Java or Python?"
user: {_id: "5bd99816068dee45fddf317e", username: "Karolina"}
voted: (2) ["5bd99816068dee45fddf317e", "5bd2ef4f755aa221a9cc6f6d"]
__v: 2
_id: "5bd9982f068dee45fddf317f"
__proto__: Object
实际上,这给了我价值
let uu;
if (poll.user) {
uu = poll.user._id;
}
console.log(uu);
答案 0 :(得分:0)
尝试
let userId = null;
if(poll && poll !== undefined && poll.user !== undefined && poll.user._id && poll.user._id !== undefined)
userId = poll.user._id;
console.log(userId )
答案 1 :(得分:0)
您可以使用下面的&&运算符同时获取用户ID和用户名
const userId = poll && poll.user && poll.user._id;
const userName = poll && poll.user && poll.user.username;