【问题标题】: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有没有一种简单的方法来遍历一个对象的值是对象数组的对象,以从这些对象的值生成一个列表
【发布时间】:2019-11-04 08:03:00
【问题描述】:

我有一个 JSON 对象要导入到类似于以下内容的反应页面中:

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>

有什么好办法吗?谢谢!

【问题讨论】:

  • 标题有点难读,你的意思是一个数组,里面有生成值的函数数组吗?

标签: javascript arrays loops object


【解决方案1】:

您可以尝试展平数组并通过它进行映射以提取值

Object.values(obj1).flat().map((a)=> a.Category)

如果数组总是一维的,你可以省略flat()

结果:

["some category 1", "some category 2", "some category 3", "some category 4", "some category 5"]

【讨论】:

  • @BelminBedak 不,flatMap 是“先映射后展平”,这里我们需要先展平然后再映射。
  • 谢谢,这正是我要找的!
【解决方案2】:

如果underscore 是我会选择的选项:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 2023-01-08
    相关资源
    最近更新 更多