首页 > 解决方案 > 从对象属性获取日期值 - javascript

问题描述

我怎样才能只从下面的对象中获取没有字符串值的日期?

0: {2020-09-02: "string_1", 2020-09-03: "string_2"}
1: {2020-09-01: "string_1", 2020-09-05: "string_2"}

我的目标是只获取日期并将它们分组到一个数组中。

预期结果:[2020-09-02, 2020-09-03, 2020-09-01, 2020-09-05]

到目前为止我尝试的是使用Object.getOwnPropertyNames

console.log('property name: ', Object.getOwnPropertyNames(getDateProperties)) // return ["0","1"]

这有可能实现吗?

标签: javascriptarrays

解决方案


使用 reduce 和 Object 键从对象中获取日期

const list = [{
    "2020-09-02": "string_1",
    "2020-09-03": "string_2"
  },
  {
    "2020-09-01": "string_1",
    "2020-09-05": "string_2"
  }
]
const result = list.reduce((acc, x) => {
  const keys = Object.keys(x)
  acc = [...acc, ...keys]
  return acc;
}, [])
console.log(result)


推荐阅读