我有一个 JSON 对象,正在导入到类似于以下内容的 React 页面中:
const obj1 = {
"January": [
{
"Id": 1,
"FileName": "some file",
"Format": "Excel (.xlsx)",
"Category": "some category 1",
"Start": "01/01/2019",
"End": "12/31/2019",
"Created": "01/09/2019"
},
{
"Id": 2,
"FileName": "some big file",
"Format": "Excel (.xlsx)",
"Category": "some category 2",
"Start": "01/01/2018",
"End": "12/31/2018",
"Created": "01/09/2019"
}
],
"February": [
{
"Id": 3,
"FileName": "some small file",
"Format": "PDF (.pdf)",
"Category": "some category 3",
"Start": "01/01/2018",
"End": "12/31/2018",
"Created": "01/09/2019"
},
{
"Id": 4,
"FileName": "some other file",
"Format": "Excel (.xlsx)",
"Category": "some category 4",
"Start": "01/01/2018",
"End": "12/31/2018",
"Created": "01/09/2018"
}
],
"March": [
{
"Id": 55,
"FileName": "some file again",
"Format": "Excel (.xlsx)",
"Category": "some category 5",
"Start": "01/01/2017",
"End": "12/31/2017",
"Created": "01/09/2017"
}
]
};
我想循环遍历上述对象,并使用每个唯一类别动态填充选择下拉元素的选项。
选择看起来像这样:
<select className="selectpicker" data-width="fit" value="All" onChange={this.addSomeOptions}>
<option >Category 1</option>
<option >Category 2</option>
<option >Category 3</option>
</select>
有什么好的方法吗?谢谢!
最佳答案
您可以尝试展平数组并通过它进行映射以提取值
Object.values(obj1).flat().map((a)=> a.Category)
如果数组始终是一维,则可以省略 flat()
结果:
["some category 1", "some category 2", "some category 3", "some category 4", "some category 5"]
关于javascript - 有没有一种简单的方法可以循环遍历一个对象,该对象的值是对象数组,以从这些对象的值生成列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58689288/