我有一个要导入到类似于以下内容的React页面中的JSON对象:
gm.gameOver()
,我想遍历以上对象,并使用每个唯一类别动态填充选择下拉列表元素的选项。
选择内容如下所示:
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"
}
]
};
有没有很好的方法可以做到这一点?谢谢!
答案 0 :(得分:2)
您可以尝试展平数组并通过其映射以提取值
Object.values(obj1).flat().map((a)=> a.Category)
如果数组始终为一维,则可以省略flat()
结果:
["some category 1", "some category 2", "some category 3", "some category 4", "some category 5"]
答案 1 :(得分:0)
如果我选择underscore
:
let Categories = [];
for (let x of obj1) {
Categories.push(x.Category);
}
let uniqueCategories = _.uniqWith(Categories, _.isEqual);
return uniqueCategories;