【问题标题】:How to loop array and output the values inside an array of objects as 'value' and 'label'?如何循环数组并将对象数组中的值输出为“值”和“标签”?
【发布时间】:2019-09-21 10:10:27
【问题描述】:

我有以下数据作为单独文件中的对象数组

export const usersRowData = [
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "value": "Leanne Graham",
    "label": "Leanne Graham"
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    }
  }
]

在我的反应组件中,我将这些过滤器数据硬编码为值和标签:

const filters = [
  {
    label: "name",
    options: [
      { value: "Dietrich", label: "Dietrich" },
      { value: "Patricia", label: "Patricia" }
    ]
  },
  {
    label: "username",
    options: [
      { value: "Kamren", label: "Kamren" },
      { value: "Bret", label: "Bret" }
    ]
  },
  {
    label: "email",
    options: [{ value: "Sincere@april.biz", label: "Sincere@april.biz" }]
  }
];

如何在我的反应组件中循环输出每个名称作为值和标签的数组,以便我可以将它们显示在列表中。

【问题讨论】:

  • 你是问如何取usersRowData 并拉出名字吗?你的filters 代码在这个问题的上下文中有什么意义?

标签: javascript arrays reactjs object ecmascript-6


【解决方案1】:

你是说像选项和价值一样显示?

const filters = [
  {
    label: "name",
    options: [
      { value: "Dietrich", label: "Dietrich" },
      { value: "Patricia", label: "Patricia" }
    ]
  },
  {
    label: "username",
    options: [
      { value: "Kamren", label: "Kamren" },
      { value: "Bret", label: "Bret" }
    ]
  },
  {
    label: "email",
    options: [{ value: "Sincere@april.biz", label: "Sincere@april.biz" }]
  }
];

function App() {
  return (
    <section>
    {filters.map(data => {
      const label = <label> {data.label} </label>
      return (
        <section>
            {label}
          <select>
            {data.options.map(option => {
              return(
                <option value={option.value}> {option.value} </option>
              )
            })}
          </select>
        </section>
      )
    })}
    </section>
  )
}

【讨论】:

    【解决方案2】:

    从您的其他文件中导入它们:

    import { usersRowData as filters } from "./otherFile";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2021-07-21
      • 2023-01-25
      • 2013-12-22
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      相关资源
      最近更新 更多