作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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/
我是一名优秀的程序员,十分优秀!