【问题标题】:render nested arrays with react by display key only once仅通过显示键渲染嵌套数组一次
【发布时间】:2020-06-12 09:00:40
【问题描述】:

我有一个嵌套数组,我想用 JSX 代码渲染这个数组,这样像 array1 这样的键应该显示一次,文本应该显示为列表,然后使用下一个数组继续相同的循环。我曾尝试使用 map 函数和 for 循环,但未能成功。

sampleArray : [{"array1": [ {"text": "abc"},{"text": "def"}, {"text": "ghi"}],
               "array2":[{"text": "efg"}, {"text": "fgh"}]]

请建议我使用 map 函数来迭代这个数组以渲染成 JSX 代码。谢谢

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    嘿,我不知道您是否在对象中犯了错误,但这里有两个版本的此实现与您的对象和我的更新:

    在 TypeScript 中忽略输入

    export const Test = ({ className }: Test) => {
      const sampleArray = [
        {
          array1: [{ text: 'abc' }, { text: 'def' }, { text: 'ghi' }],
          array2: [{ text: 'efg' }, { text: 'fgh' }],
        },
      ]
    
      const sampleArray2 = [
        {
          array1: [{ text: 'abc' }, { text: 'def' }, { text: 'ghi' }],
        },
        {
          array2: [{ text: 'efg' }, { text: 'fgh' }],
        },
      ]
      return (
        <>
          {/* YOUR VERSION */}
          <div>
            {Object.keys(sampleArray[0]).map((key) => {
              return (
                <div>
                  <div id="title">{key}</div>
                  {sampleArray[0].map((item) => {
                    return <div>{item.text}</div>
                  })}
                </div>
              )
            })}
          </div>
          {/* UPDATED VERSION */}
          <div>
            {sampleArray2.map((key) => {
              const title = Object.keys(key)[0]
              return (
                <div>
                  <div id="title">{title}</div>
                  {key[title].map((item) => {
                    return <div>{item.text}</div>
                  })}
                </div>
              )
            })}
          </div>
        </>
      )
    }
    
    

    【讨论】:

    • 感谢版本 2。我已经更改了我的数据结构并且它有效。
    猜你喜欢
    • 2019-05-12
    • 2021-10-04
    • 2016-04-25
    • 2018-03-05
    • 2016-06-20
    • 1970-01-01
    • 2020-07-14
    • 2023-02-16
    • 1970-01-01
    相关资源
    最近更新 更多