【问题标题】:How can I get specific object key in map iteration如何在地图迭代中获取特定的对象键
【发布时间】:2019-05-30 07:54:11
【问题描述】:

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

    }

}

【问题讨论】:

  • 结果应该是什么?
  • 你有一个错字:item.conten._url
  • 我知道这不会改变任何事情
  • 我想将`content._url`返回到image ?
  • image: (item.content && item.content._url) ? item.content._url : '' 应该足够了。

标签: javascript arrays json object iteration


【解决方案1】:

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

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 会引发异常。像我上面那样添加一个三元运算符将确保该属性存在,否则它将默认值设置为''。如果这不是预期的默认值,请随意更改它。

【讨论】:

    【解决方案2】:

    首先你必须得到项目键和它一个数组。让我们遍历它并获取您要获取的密钥

    let jsonData = {
        "item": [
      
          {
             "title": "title",
             "link": "link",
             "content": {
              "_url": "How can I get this :D"
             }
          }
      
         ]
      }
       function getKeyFromObject(obj,key){
    
              return obj.item.map(each=>each.content[key])
          }
          
      const url = getKeyFromObject(jsonData,"_url");
      console.log(url);

    【讨论】:

      【解决方案3】:

      试试

      return {
         title: item.title, 
         link: item.link,
         image: item['content']['_url'], 
         id: item.guide,
      }
      

      【讨论】:

        猜你喜欢
        • 2018-04-06
        • 2012-09-04
        • 2016-02-08
        • 2020-05-15
        • 1970-01-01
        • 2022-06-30
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        相关资源
        最近更新 更多