简体   繁体   English

渲染嵌套的 arrays 并仅通过显示键反应一次

[英]render nested arrays with react by display key only once

I have a nested array and I would like to render this array with JSX code such that key like array1 should be display once and the text should be displayed as list and then continue the same loop with the next array.我有一个嵌套数组,我想用 JSX 代码渲染这个数组,这样像 array1 这样的键应该显示一次,文本应该显示为列表,然后使用下一个数组继续相同的循环。 I have tried using map function and for loop but could not achieve success.我曾尝试使用 map function 和 for 循环,但未能成功。

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

Please suggest me map function to iterate over this array to render into JSX code.请建议我 map function 遍历此数组以呈现 JSX 代码。 Thanks谢谢

Hey I don't know if you made a mistake in your object, but here are two versions of this implementation with your object and with my update:嘿,我不知道您是否在 object 中犯了错误,但这里有两个版本的此实现与您的 object 和我的更新:

Ignore typings did it in TypeScript忽略类型在 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>
    </>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM