使用地图时如何检查值?

Uza*_*San 0 javascript arrays

我正在将一些对象转换为 JSON:

const tpL = results.map(post => ({
    ...post.toJSON(),
    postid: post.get("comment").id,
    commentid: post.get("post").id
  }));
Run Code Online (Sandbox Code Playgroud)

但是post.get("comment")orpost.get("post")在每个对象中都没有定义。所以我必须先检查是否post.get("comment")存在。

我怎样才能做到这一点?

Cer*_*nce 5

这听起来像是可选链接的一个很好的用例:

const tpL = results.map(post => ({
    ...post.toJSON(),
    postid: post.get("comment")?.id,
    commentid: post.get("post")?.id
}));
Run Code Online (Sandbox Code Playgroud)

如果.get返回 null 或 undefined,则生成的属性值将为undefined

这是一种相对较新的语法,因此尚未在所有地方都受支持。(如果你把它放在一个公共网站上,希望你的脚本已经被 Babel 转译以实现跨浏览器兼容性)