【问题标题】:How to properly make a .map in js如何在js中正确制作.map
【发布时间】:2019-11-16 07:45:39
【问题描述】:

谁能帮我提取带有href 的所有链接?

这是map 代码:

const image = images.map(img => img.links)

{ image.map(a => a.map( b => b.href))}

还有其他方法吗?

这是数据

{
  'item': [
    {
      'data': [
        {'href': link}
      ]
    },
  ...
    {
      'data': [
        {'href': link}
      ]
    },
  ]
}

【问题讨论】:

  • 你能再分享一些代码吗,你在做什么,你在解析什么?
  • 我有一个 API link,我需要将所有图像放入我的反应组件中
  • 你希望你的输出是什么样子的?只需分享 JSON 对象的格式即可。
  • const ImagesGallery = ({images}) => { useEffect( () => { onImagesGallery() }, [onImagesGallery]) const image = images.map(img => img.links) return ( { image.map(a => a.map( b => <div className={style.wrapper__container__content} key={b.index}> <img src={b.href ? b.href : noImage} alt=""/> </div> )) } ) } const mapStateToProps = state => ({ images: state.imagesGalleryPage.items, })

标签: javascript arrays reactjs object


【解决方案1】:

如果你有如下结构,那么使用flatmap函数:

const data = [
  {
    'item': [
      {
        'data': [
          { 'href': 'link' },
          { 'href': 'link2' }
        ]
      }
    ]
  },
  {
    'item': [
      {
        'data': [
          { 'href': 'link' },
          { 'href': 'link3' },
        ]
      },
    ]
  }
];

 const result = data.flatMap(d =>
    d.item.flatMap(i =>
        i.data.map(h => h.href)));

 console.log(result);

【讨论】:

    【解决方案2】:

    另一个不涉及使用.map 的解决方案是使用JSONPath,它有助于通过带有集合的JSON 对象进行查询。

    在您的情况下,您可以执行以下操作:$.[*]..href 以便将每个 href 放入数组中。

    JSONPath 类似于 xPath,它是一种查询语言,可以帮助您从集合/记录中检索数据。

    更多关于 JSONPath 的信息:https://restfulapi.net/json-jsonpath/

    在线游乐场:https://jsonpath.com

    我在 npm 中找到的一个快速库:https://www.npmjs.com/package/jsonpath

    【讨论】:

    • 这是一个很好的想法,我在反应组件中与 .map 一起使用,并且想法与此无关
    【解决方案3】:

    您可以使用 Array.mapArray.filter 循环遍历对象的 'item' 来归档它

    var myItem = {
        'item': [
          {
            'data': [
              {'href': 'link1'}
            ]
          },
          {
            'data': [
              {'href': 'link2'}
            ]
          }
        ]
      }
    
    var links = myItem['item'].map(el => el.data).reduce((rs, el)=> [...rs, el[0].href], [])
    console.log(links)
    

    【讨论】:

      【解决方案4】:

      在处理嵌套集合时,您通常希望展平结果数据结构。 所以你先做flatMap,然后是map

      json.item.flatMap(x => x.data.map(image => image.href)) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 2018-03-31
        • 2014-10-16
        • 2019-09-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多