Javascript 使用map时如何检查值?
我正在将一些对象转换为JSON:Javascript 使用map时如何检查值?,javascript,arrays,Javascript,Arrays,我正在将一些对象转换为JSON: const tpL = results.map(post => ({ ...post.toJSON(), postid: post.get("comment").id, commentid: post.get("post").id })); 但是并非每个obejct中都定义了post.get(“comment”)或post.get(“post”)。因此,我必须首先检查post.get(“
const tpL = results.map(post => ({
...post.toJSON(),
postid: post.get("comment").id,
commentid: post.get("post").id
}));
但是并非每个obejct中都定义了post.get(“comment”)
或post.get(“post”)
。因此,我必须首先检查post.get(“comment”)
是否存在
我如何才能做到这一点?由于并非所有环境都支持可选链接,我建议您执行以下操作:
const tpL = results.map(post => ({
...post.toJSON(),
...(post.get("comment") && { postid: post.get("comment").id }),
...(post.get("post") && { commentid: post.get("post").id })
}));
这样,只有定义了
.get(“comment”)
时,数组的对象才会包含postid
,只有定义了.get('post')
时,数组的对象才会包含commentid
。这听起来像是一个很好的用例:
如果.get
返回null或undefined,则生成的属性值将undefined
这是一种相对较新的语法,因此还没有在任何地方都支持它。(如果你把它放在一个公共网站上,希望你的脚本已经通过Babel进行了跨浏览器兼容性传输)
const tpL=results.map(post=>({
…post.toJSON(),
postid:post.get(“comment”)?post.get(“comment”).id:null,
commentid:post.get(“post”)?post.get(“post”).id:null
}));代码>其他答案有效且优雅,但您可能会忽略,您也可以使用完整的代码块作为传递给map()
的函数体,而不仅仅是表达式(其中({/*code省略*/})
)。所以你也可以写
const tpL = results.map(post => {
const res = post.toJSON();
if (post.get("comment")){
res.postid = post.get("comment").id;
}
if (post.get("post")){
res.commentid = post.get("post").id;
}
return res;
});
如果.get
没有返回任何内容,您希望属性的结果值是什么?未定义?@CertainPerformance我想跳过那部分。我不想设置任何东西,我将在nodejs 12中使用thin。这会是一个问题吗?取决于生产环境,如果它也要使用节点12,那么就没问题了。我得到了这个错误。postid:post.get(“comment”)?.id,^SyntaxError:Unexpected token'.@UzaySan如果它总是在支持可选链接的环境中运行,那么就没有问题了,试试吧。但节点14首先支持可选链接。如果是我,我会升级节点版本。
const tpL = results.map(post => {
const res = post.toJSON();
if (post.get("comment")){
res.postid = post.get("comment").id;
}
if (post.get("post")){
res.commentid = post.get("post").id;
}
return res;
});