我有一个 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/