javascript - 如何在 map 迭代中获取特定对象键

标签 javascript arrays json object iteration

我有一个 json 文件,我用 map 对其进行迭代,但我有一个名为“content”的深层对象键,当我用 map 返回我的 json 数组时,我想从中获取特定的键

JSON:

{
  "item": [

    {
       "title": "...",
       "link": "...",
       "content": {
        "_url": "How can I get this :D",
        ...
       }
    }

   ]
}

我的 javascript 代码:

getAllNews = async () => {
    const result = await this.getResource('item/')

    return result.map(this._transformPosts) 
    // Here I iterate my json

}

_transformPosts = (item) => {

    return {
       title: item.title, 
       link: item.link,
       image: item.content._url, 
       // and here I try get _url
       id: item.guide,

    }

}

最佳答案

要正确处理所有情况,请记住始终检查属性是否有效存在:

return {
       title: item.title, 
       link: item.link,
       image: (item.content && item.content._url) ? item.content._url : '', // <-- fix here.
       id: item.guide,

    }

可能的问题可能是:

  • 您的行中有错别字:item.conten._url,(应为content)
  • item 缺少 content。在这种情况下,item.content._url 会引发异常。像我上面那样添加一个三元运算符将确保该属性存在,否则它会将默认值设置为 ''。如果这不是预期的默认值,请随意更改它。

关于javascript - 如何在 map 迭代中获取特定对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56374016/

相关文章:

javascript - 如何更新 jQuery 的 .data() 存储的 "complex"数据?

c - 操作函数中的整数数组时发生堆栈粉碎错误

python - 使用 django 在 python 中将 Model.Objects.all() 转换为 JSON

javascript - 使用javascript从php获取json数据

javascript - 有没有一种简单的方法可以将文件链接变成下载按钮?

javascript - 编辑 ckeditor config.js 没有影响

javascript - 循环绑定(bind)对象

arrays - 从Powershell中的对象中删除一个或多个成员

c# - 来自数组中对象元素的数组

javascript - 日期以字符串格式出现在 json 对象中。我想要它的日期格式,因为我想显示它