繁体   English   中英

有没有一种简单的方法来循环一个 object 的值是对象的 arrays 以从这些对象的值生成一个列表

[英]Is there a simple way to loop through an object who's values are arrays of objects to generate a list from those object's values

我有一个 JSON object 我正在导入类似于以下内容的反应页面:

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 下拉元素的选项。

select 看起来像这样:

<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"]

如果underscore是一个选项我会 go 与:

let Categories = [];
for (let x of obj1) {
    Categories.push(x.Category);
}
let uniqueCategories = _.uniqWith(Categories, _.isEqual);
return uniqueCategories;

暂无
暂无

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

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